Given an array of integers, find a maximum sum of non-adjacent elements. For example, inputs [1, 0, 3, 9, 2,-1] should return 10 (1 + 9).
Let BEST_SUM(i)
be the maximum sum of non-adjacent elements at positions <= i
.
When i<0, BEST_SUM(i) = 0
Otherwise: BEST_SUM(i) = max( BEST_SUM(i-1), BEST_SUM(i-2)+a[i] )
BEST_SUM(a.length-1)
is your answer.
NOTE: This is the max sum of non-adjacent elements, like you asked for. Looking at your code it looks like you may mean the best sum of two non-adjacent elements. The would be different, and easier.