Algorithm to find the maximum subsequence of an array of positive numbers . Catch : No adjacent elements allowed

前端 未结 13 1125
甜味超标
甜味超标 2020-12-24 04:42

For example, given

A = [1,51,3,1,100,199,3], maxSum = 51 + 1 + 199 = 251.

clearly max(oddIndexSum,evenIndexSum) does not

13条回答
  •  粉色の甜心
    2020-12-24 05:04

    To avoid recursion, we can take from reverse than forward,

    ie) for Array A[1..n]->

         maxSum(A,n): for all n
    
             if n=0, maxSum = 0 else
             if n=1, maxSum=A[1] else
                    maxSum = max(A[n] + maxSum(A,n-2), maxSum(A,n-1))
    

    To avoid computing of Max(A,n-2), while expanding maxSum(A,n-1), it can be stored and computed. That is why I ask to reverse. ie) maxSum(A,n-1) = max(A[n-1]+ maxSum(A,n-3), maxSum(A,n-2) ) where in Max(A,n-2) is already got, and no need to recalculate ) In otherwords compute maxSum(A,n) for all n starting from 1 to n using above formula to avoid recomputing.

    ie) n=2, maxSum = max(A[1]+maxSum(A,0), maxSum(A,1) ) ie) n=3, maxSum = max(A[2]+maxSum(A,2), maxSum(A,2) ) and so on .. and reach last n. this will be o(n).

提交回复
热议问题