Given an array of positive integers, what's the most efficient algorithm to find non-consecutive elements from this array which, when added together, produce the maximum sum?
The dynamic programming solution is to use an auxiliary array maxSum holding the max sum up until that particular index. We start by setting the first 2 indices of the array, and fill the rest of the array with max(array[i]+maxSum[i-2], maxSum[i-1]).
I understand that we cannot add adjacent elements, but I am struggling to understand how the above solution takes into consideration that it is possible for the the previous element in maxSum[i] to not be the result of summing with array[i].
For example:
index: 0 1 2 3 4
array: 3 5 -7 8 10
maxSum: 3 5 5 _
We see that maxSum[2] is not a result of summing with array[2].
To find maxSum[3] = max(array[3]+maxSum[1], maxSum[2]), but why don't we consider maxSum[2] + array[3]? Since it is possible for maxSum[2] to not consist of the adjacent array[2] value.