lc.algoro.dev
← Back to problems

Maximum Subarray

Medium #53 View Problem ↗ Array • Divide and Conquer • Dynamic Programming

Intuition

You want the largest possible sum of a contiguous subarray.

As you scan left→right, any running sum that dips below zero is a liability—adding it to future elements can only make them smaller. So, the best prefix to carry forward is either:


Approach

  1. Maintain two values while iterating:
  1. For each x:
  1. Return best. Edge cases

Proof of Correctness

We prove by induction on the index i:

Thus, by induction, at the end best is the maximum subarray sum.


Complexity


Code

TypeScript Solution
export function maxSubArray(nums: number[]): number {
  let curr = nums[0];
  let best = nums[0];

  for (let i = 1; i < nums.length; i++) {
    const x = nums[i];
    curr = Math.max(x, curr + x);
    best = Math.max(best, curr);
  }
  return best;
}
Python Solution
def maxSubArray(self, nums):
    curr = nums[0]
    best = nums[0]

    for x in nums[1:]:
        curr = max(x, curr + x)
        best = max(best, curr)
    return best