Algorithm to find maximum sum of elements in an array such that not more than k elements are adjacent

前端 未结 2 1392
长发绾君心
长发绾君心 2021-01-05 04:59

I came across this question. Given an array containing only positive values, you want to maximize the sum of chosen elements under the constraint that no group of more than

2条回答
  •  旧时难觅i
    2021-01-05 05:43

    I think this will work :

    findMaxSum(int a[], int in, int last, int k) { // in is current index, last is index of last chosen element
        if ( in == size of a[] ) return 0;
        dontChoseCurrent = findMaxSum(a, in+1, last, k); // If current element is negative, this will give better result
        if (last == in-1 and k > 0) { // last and in are adjacent, to chose this k must be greater than 0
            choseCurrentAdjacent = findMaxSum(a, in+1, in, k-1) + a[in];
        }
        if (last != in-1) { // last and in are not adjacent, you can chose this.
            choseCurrentNotAdjacent = findMaxSum(a, in+1, in, k) + a[in];
        }
        return max of dontChoseCurrent, choseCurrentAdjacent, choseCurrentNotAdjacent
    }
    

提交回复
热议问题