The running time should be O(n), this is what I came up with, is it correct? THANKS
for (i = 1 ; i < A[n]; i++)
A[i] = 0
B[i] = 0;
for i in A[1..n]
B[i] = B[i] + A[i]
Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.
Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.
Lost your password? Please enter your email address. You will receive a link and will create a new password via email.
Please briefly explain why you feel this question should be reported.
Please briefly explain why you feel this answer should be reported.
Please briefly explain why you feel this user should be reported.
Yes, this is correct. Your solution is the most trivial case of dynamic programming, a technique to greatly speed up algorithms for solutions that can be constructed from solutions from smaller sub-problems.
Your problem at hand has precisely this property: a solution to
B[n]can be constructed inO(1)if you are given a solution toB[n-1], and that is what your algorithm did, for a running time ofO(N).Solutions like that are very helpful in practice: I once used an algorithm like yours to speed up a piece of start-up code in my program from several minutes to several seconds (it was adding vectors, so it went from
O(3)toO(2)).