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

前端 未结 13 1153
甜味超标
甜味超标 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

    A recursive answer in strange Prologesque pseudocode:

    maxSum([]) = 0
    maxSum([x]) = x
    maxSum(A) = max(A[0] + maxSum(A[2..n]),
                    A[1] + maxSum(A[3..n]))
    

    With appropriate handling of out-of-range indexes.

    Edit: This reduces to MarcusQ's nicer answer:

    maxSum([]) = 0
    maxSum(A) = max(A[0] + maxSum(A[2..n]), maxSum(A[1..n]))
    

    Edit: Here's a version that returns the actual subsequence rather than just its sum. It stretches the limits of my ad hoc pseudo-Prolog-C Chimera, so I'll stop now.

    maxSub([]) = []
    maxSub(A) = sub1 = [A[0]] + maxSub(A[2..n])
                sub2 = maxSub(A[1..n])
                return sum(sub1) > sum(sub2) ? sub1 : sub2
    

提交回复
热议问题