"k", : fooobar.com/questions/269212/...
The above solution, in my opinion, can be easily extended to have a k constraint by simply changing the if condition in the following for the loop to include the constraint: possibleMax <k
for (int i = start; i <= end; i++) {
int possibleMaxSub1 = maxSum(a, i + 2, end);
int possibleMaxSub2 = maxSum(a, start, i - 2);
int possibleMax = possibleMaxSub1 + possibleMaxSub2 + a[i];
if (possibleMax > maxSum && possibleMax < k) {
maxSum = possibleMax;
}
}
As indicated in the source link, this approach can be improved by adding memorization so that the solutions of the repeating routines are not recounted. Or it can be improved using a dynamic bottom-up approach (the current approach is a recursive top-down approach)
You can refer to the bottom-up approach: fooobar.com/questions/269212 / ...
source
share