0

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

4
  • I don't see how this is language-related. Commented Aug 28, 2012 at 20:55
  • 2
    Not sure, but isn't that one of the prototypical examples for dynamic programming? (en.wikipedia.org/wiki/Dynamic_programming) Commented Aug 28, 2012 at 20:57
  • I think the max sum is -6: 0 1 8 -10 -1 -4 0 Commented Aug 28, 2012 at 21:01
  • yes that's right, sorry) Commented Aug 28, 2012 at 21:04

1 Answer 1

3

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
Sign up to request clarification or add additional context in comments.

1 Comment

Good point! (I moved the comment here because I delete my answer) +1

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.