-2

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?

Fadedrifleman
  • 197
  • 2
  • 12
  • What is the case where ```currentSum === maxSum ``` ? – Srushti Shah May 01 '23 at 14:10
  • 3
    [4, 2, 2, 1, 5, 3] why is it not the sum of all the numbers – cmgchess May 01 '23 at 14:13
  • You reset `currentSum` to zero when it's less than zero, but what if the input array has all negative numbers, some closer to zero and others farther? The max sum might be less than zero. – Pointy May 01 '23 at 14:18
  • @SrushtiShah I believe that will never be the case as every time we go to the loop, some value is added or subtracted from the `currentSum`, so it can never be equal to `maxSum`, at least till the loop is running – Fadedrifleman May 01 '23 at 14:21
  • Your logic is a bit odd. Why would currentsum be set to 0 like that? They are asking for the maximum sum, not the maximum sum if it happens to be greater than 0. Perhaps start by thinking of this array [-1] – A Haworth May 01 '23 at 14:22
  • The comment from @cmgchess is important: if the array contains all positive numbers, then no sub-sequence can sum to more than the entire array (discounting the degenerate case of some values being 0, where there are multiple answers). – Pointy May 01 '23 at 14:28
  • @AHaworth thanks, that completely makes sense, works now – Fadedrifleman May 01 '23 at 14:29
  • this is actually a famous problem and can be found in clrs. i had a java code with me which uses divide and conquer. i converted it to [js](https://gist.github.com/cmgchess/bbb43b02b01bcc7642ce83010ea91b9d) – cmgchess May 01 '23 at 14:47
  • plenty of duplicates: [JavaScript algorithm question: get the find the contiguous subarray which has the largest sum from an array](https://stackoverflow.com/questions/65558214/javascript-algorithm-question-get-the-find-the-contiguous-subarray-which-has-th), [Maximum subarray problem - min value solution?](https://stackoverflow.com/questions/66408197/maximum-subarray-problem-min-value-solution) [Javascript function that finds largest subarray](https://stackoverflow.com/questions/62730006/javascript-function-that-finds-largest-subarray), etc – pilchard May 01 '23 at 18:01

1 Answers1

1

So:

  1. First get all subarrays.
  2. Calculate sum of each subarray.
  3. 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.length && 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.

Thomas Frank
  • 1,404
  • 4
  • 10