For example, given
A = [1,51,3,1,100,199,3], maxSum = 51 + 1 + 199 = 251.
clearly max(oddIndexSum,evenIndexSum) does not
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.