Maximum contiguous sum of subarray in JavaScript


We are required to write a JavaScript function that takes in an array of array of positive and negative integers. Since the array also contains negative elements, the sum of contiguous elements can possibly be negative or positive.

Our function should pick an array of contiguous elements from the array that sums the greatest. Finally, the function should return that array.

For example −

If the input array is −

const arr = [-2, -3, 4, -1, -2, 1, 5, -3];

Then the maximum possible sum is 7 and the output subarray should be −

const output = [4, -1, -2, 1, 5];

Example

Following is the code -

const arr = [-2, -3, 4, -1, -2, 1, 5, -3];
const maximumSubarray = (arr = []) => {
   let max = -Infinity;
   let currentSum = 0;
   let maxStartIndex = 0;
   let maxEndIndex = arr.length - 1;
   let currentStartIndex = 0;
   arr.forEach((currentNumber, currentIndex) => {
      currentSum += currentNumber;
      if (max < currentSum) {
         max = currentSum;
         maxStartIndex = currentStartIndex;
         maxEndIndex = currentIndex;
      }
      if (currentSum < 0) {
         currentSum = 0;
         currentStartIndex = currentIndex + 1;
      }
   });
   return arr.slice(maxStartIndex, maxEndIndex + 1);
};
console.log(maximumSubarray(arr));

Output

Following is the output on console −

[ 4, -1, -2, 1, 5 ]

Updated on: 11-Dec-2020

223 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements