Maximum Subarray - JS Solution

JS
Editorial

Solution explanation

Solution explanation

Approach

Goal

Given an integer array nums, find the contiguous subarray (containing at least one number) which has the largest sum and return its sum.

Key Idea (Intuition)

At each index, we decide whether to extend the best subarray ending at the previous index or start a new subarray at the current index. If the running sum up to the previous index is negative, then starting fresh at the current index yields a larger value for maxEndingAtIndex than extending the negative sum. Otherwise, it is better to extend the previous subarray by adding the current element.

Initialization

  • maxEndingAtIndex = nums[0] — best subarray sum that ends at index 0.
  • maxSoFar = maxEndingAtIndex — global best sum seen so far.
  • Start traversal at i = 1.

Traversal

For each index i from 1 to n - 1:

  1. Update the best ending here:
    maxEndingAtIndex = max(maxEndingAtIndex, 0) + nums[i]
    (If maxEndingAtIndex was negative, reset to 0 to start a new subarray at i; otherwise, extend the previous subarray.)
  2. Update the global best:
    maxSoFar = max(maxSoFar, maxEndingAtIndex)

Return

After the loop, return maxSoFar as the maximum subarray sum.

Time Complexity

We make a single pass over the array, performing O(1) work at each index. Therefore, the time complexity is O(n), where n is the length of the array.

Space Complexity

The algorithm maintains only a constant number of variables (maxEndingAtIndex, maxSoFar, and index). No additional data structures are used. Therefore, the space complexity is O(1).

Visucodize editorial solution titled JS Solution for LeetCode's Maximum Subarray coding problem. Includes code and may include explanation. You can animate the code step by step using the provided input by clicking the run button, or fork it locally to update the code and input for custom visualization. View the original problem at https://leetcode.com/problems/maximum-subarray.