Finding the sub array that has maximum sum JavaScript

We are required to write a JavaScript function that takes in an array of numbers. The array can contain both positive and negative numbers.

The purpose of our function is to find the subarray (of any length) whose elements when summed give the maximum sum. This problem is known as the Maximum Subarray Problem and is commonly solved using Kadane's Algorithm.

For example, if the input array is:

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

Then the output should be:

6

Because the subarray [4,-1,2,1] has the largest sum of 6.

How Kadane's Algorithm Works

Kadane's algorithm uses dynamic programming to solve this problem efficiently in O(n) time complexity. The key insight is to keep track of the maximum sum ending at each position.

Array: [-2, 1, -3, 4, -1, 2, 1, -5, 4] Current Sum: Max Sum: -2 -2 1 1 -2 1 4 4 3 4 5 5 6 6 1 6 5 6 Max: 6 Optimal subarray: [4, -1, 2, 1]

Example

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

const maxSubArray = (arr = []) => {
    let sum = arr[0], max = arr[0];
    for (let i = 1; i 

Output

6

Step-by-Step Explanation

The algorithm works by maintaining two variables:

  • sum: Maximum sum of subarray ending at current position
  • max: Maximum sum found so far

At each element, we decide whether to extend the existing subarray or start a new one by comparing sum + arr[i] with arr[i].

Alternative Implementation with Subarray Tracking

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

const maxSubArrayWithIndex = (arr = []) => {
    let maxSum = arr[0];
    let currentSum = arr[0];
    let start = 0, end = 0, tempStart = 0;
    
    for (let i = 1; i  maxSum) {
            maxSum = currentSum;
            start = tempStart;
            end = i;
        }
    }
    
    console.log(`Maximum sum: ${maxSum}`);
    console.log(`Subarray: [${arr.slice(start, end + 1).join(', ')}]`);
    console.log(`Indices: ${start} to ${end}`);
    
    return maxSum;
};

maxSubArrayWithIndex(arr);

Output

Maximum sum: 6
Subarray: [4, -1, 2, 1]
Indices: 3 to 6

Conclusion

Kadane's Algorithm efficiently solves the maximum subarray problem in O(n) time complexity. It's a classic example of dynamic programming where we make optimal decisions at each step to find the global maximum.

Updated on: 2026-03-15T23:19:00+05:30

566 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements