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

前端 未结 13 1151
甜味超标
甜味超标 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 04:55

    We can use an auxiliary array B[0..n-1], where B[i] is the maximum sum of the elements A[0..i] and C[0..n-1], where C[i] is boolean telling if A[i] is in the maximum sum subsequence:

    B[0]=max(A[0],0); C[0]=(A[0]>0)
    B[1]=max(B[0],A[1]); C[1]=(A[1]>B[0])
    for i in [2..n-1]
      if A[i]+B[i-2] > B[i-1]
          C[i]=True
          B[i]=A[i]+B[i-2]
      else
          C[i]=False
          B[i]=B[i-1]
    mssq=[]
    i=n-1
    while i>=0
      if C[i]
        push(A[i],mssq)
        i=i-2
      else
        i=i-1
    return mssq
    

    This clearly works in O(n) time and space. Actually, this is the same as MarcusQ's solution, only reversed and optimized.

提交回复
热议问题