Given an array of integers, find the maximum sum of any contiguous subarray of the array. For example, given the array [1, -2, 3, 10, -4, 7, 2, -5]
, the maximum sum of a contiguous subarray is 18
([3, 10, -4, 7, 2]
). This is the problem statement
My solution(not working for all test cases) :
function maxSubarraySum(arr) {
let maxSum = 0;
let currentSum = 0;
for (let i = 0; i < arr.length; i++) {
currentSum += arr[i];
if (currentSum > maxSum) {
maxSum = currentSum;
} else if (currentSum < 0) {
currentSum = 0;
}
}
return maxSum;
}
console.log(maxSubarraySum([1, -2, 3, 10, -4, 7, 2, -5]));
// Should output 18
failed testcase:
input: [-1, -2, -3, -4, -5]
expected output: -1
output:0
I have been debugging my code for a long time now, any suggestions?