Computer >> Computer tutorials >  >> Programming >> Javascript

Using Kadane’s algorithm to find maximum sum of subarray in JavaScript


Problem

We are required to write a JavaScript function that takes in an array of integers (both positive and negative), arr, as the first and the only argument.

Our function should return the maximum sum of any subarray in linear time

The local_maximum at any arbitrary index i is the maximum of arr[i] and the sum of arr[i] and local_maximum at index i - 1.

This is what we are going to apply to find the maximum subarray sum within an array in linear time.

For example, if the input to the function is −

Input

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

Output

const output = 6;

Output Explanation

Because the subarray with maximum sum is −

[4, -1, 2, 1]

Example

Following is the code −

const arr = [-2, 1, -3, 4, -1, 2, 1, -5, 4];
const maxSequence = (arr = []) => {
   let currentSum = 0
   let maxSum = 0

   for (let elem of arr) {
      const nextSum = currentSum + elem
      maxSum = Math.max(maxSum, nextSum)
      currentSum = Math.max(nextSum, 0)
   }

   return maxSum
};
console.log(maxSequence(arr));

Output

6