Given an array of integers and a value K find a subsequence having maximum sum under K.
Return the maximum Sum.
// Examples -
nums = [1,2,3,4,5,6,7,16], K = 15
// ans = 15
// explaination = [1,2,3,4,5]
nums = [1,2,3,12,3], K = 10
// ans = 9
// explaination = [1,2,3,3]
我是暴力解 -
// 2^n
static long maxSum = 0;
private static long maxSumUnderKNaive(int[] nums, int k) {
maxSum = 0;
_maxSumUnderK(nums, 0, 0, k);
return maxSum;
}
private static void _maxSumUnderK(int[] nums, int i, long sum, int k) {
if(sum > k || i == nums.length) return;
if(sum > maxSum) maxSum = sum;
_maxSumUnderK(nums, i + 1, sum + nums[i], k);
_maxSumUnderK(nums, i + 1, sum, k);
}