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
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
}