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

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

    Here is an answer done using dynamic programming using the same base concept as that used by MarkusQ. I am just calculating the sum, not the actual sequence, which can produced by a simple modification to this code sample. I am surprised nobody mentioned this yet, because dynamic programming seems a better approach rather than recursion + memoization !

    int maxSeqSum(int *arr, int size) {
      int i, a, b, c;
      b = arr[0];
      a = (arr[1] > arr[0]) ? arr[1]: arr[0];
      for(i=2;i (b + arr[i]))? a : (b + arr[i]);
        b = a;
        a = c;
      }
      return a;
    }
    

提交回复
热议问题