Alex Hoppus
Alex Hoppus

Reputation: 3935

Fastest algorithm sequentially moving through array

Suppose you have an array with positive and negative integers. If you stand on ith position you can move to i+1th or to i+2th position. The task is to find the path, how should you move, to get max sum of all collected values. What is the fastest algorithm to solve this problem? Thanks.

Example:

0 1 8 -7 -10 -30 -1 -4 -5 0

0 1 8 -10 -1 -4 0 max sum -6

Upvotes: 0

Views: 171

Answers (1)

Karoly Horvath
Karoly Horvath

Reputation: 96306

This is a classic example of dynamic programming.

For each position you will calculate the max sum attainable by reaching that position. Position i can be reached either from position i-1 or i-2, so:

maxsum[i] = max(maxsum[i-2], maxsum[i-1]) + val[i]

You just have to iterate through the array, with the starting values: maxsum[<0] = 0.

Complexity: O(n).

0 1 8 -7 -10 -30 -1 -4 -5 0

0 1 9 2  -1  -28 -2 -6 -7 -6

Upvotes: 3

Related Questions