algorithmlogickadanes-algorithm

Find max sum of elements in an array ( with twist)


Given a array with +ve and -ve integer , find the maximum sum such that you are not allowed to skip 2 contiguous elements ( i.e you have to select at least one of them to move forward).

eg :-

10 , 20 , 30, -10 , -50 , 40 , -50, -1, -3

Output : 10+20+30-10+40-1 = 89


Solution

  • Use a recurrence that accounts for that:

    dp[i] = max(dp[i - 1] + a[i], <- take two consecutives
                dp[i - 2] + a[i], <- skip a[i - 1])
    

    Base cases left as an exercise.