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?
>Solution :
So:
- First get all subarrays.
- Calculate sum of each subarray.
- Return the largest sum.
I can’t see that you are trying to get all the subarrays in your code?
One solution would be:
function largestSubSum(arr) {
// get all subarrays
let subs = arr.map((x, i, a) => a.slice(i).map((x, i, a) =>
a.slice(a, i))).flat().filter(x => x.length !== arr && x.length);
// get sums
let sums = subs.map(x => x.reduce((a, c) => a + c));
// return max sum
return Math.max(...sums);
}
console.log(largestSubSum([1, -2, 3, 10, -4, 7, 2, -5])); // => 18
console.log(largestSubSum([-1, -2, -3, -4, -5])); // => -1
In detail, how this implementation works
Getting all subarrays:
Use map to go through the array and get new arrays that are slices, first from index 0, then index 1 etc. For each of those arrays map through those too and slice in the same way. Because of how maps in maps works we now have an array of arrays of arrays, so flatten it to one single array of arrays. Then, using filter remove every array that has the same length as the whole original array (that’s not an subarray) and every empty array (length is 0/falsey). We now have an array of all subarrays.
Gettting the sum of each sub array:
Simply map through the array of arrays and use reduce on each array to calculate the sum of it. Now we have an array of sums.
Getting the largest sum:
Send all the sums as separate arguments to Math.max that will return the largest number.