Here is a function I am working with:
var data = [12,23,14,35,24];
//debugger;
function findMaxSum(dataArr, targetSum){
var currentSum = dataArr[0];
var maxSum = 0;
var start = 0;
for (var index = 1; index < dataArr.length; index++) {
while(currentSum > targetSum && start < index){
currentSum -= dataArr[start];
start++
}
maxSum = Math.max(maxSum, currentSum);
currentSum += dataArr[index];
if(currentSum <= targetSum){
maxSum = Math.max(currentSum, maxSum);
}
}
return maxSum;
}
console.log(findMaxSum(data,50));
I am aiming for a maximum sum of 50, expecting elements 12,14,24
Yet, I am only able to reach 49. What am I overlooking here?