Skip to main content
61

Maximum Subarray

Mediumgreedydynamic programming

Your code isn't saved yet: refreshing or leaving the page resets it. Saved progress comes with user accounts.

This problem uses:GreedyRead the beginner guide

Given an integer array nums, find the non-empty contiguous subarray with the largest sum, and return that sum.

Understand the problem

  • A contiguous subarray is a run of elements next to each other: in [1, -3, 4], [-3, 4] is one, but [1, 4] isn't.
  • Non-empty means you must pick at least one element, even if every number is negative.
  • You return the sum, not the subarray.

Example 1

text
Input:  nums = [-2, 1, -3, 4, -1, 2, 1, -5, 4]
Output: 6

[4, -1, 2, 1] sums to 6. Including the -1 is worth it, because the 2, 1 after it more than make up for it.

Example 2

text
Input:  nums = [5, 4, -1, 7, 8]
Output: 23

The whole array.

Example 3

text
Input:  nums = [-3, -1, -2]
Output: -1

Every number is negative, and the subarray can't be empty, so the best is the single largest: -1.

Constraints

  • 1 <= nums.length <= 10^5
  • -10^4 <= nums[i] <= 10^4

Hints

Stuck? Open one hint at a time. Each one gives away a little more than the last.

    The idea in one sentence

    Walk the array keeping a running sum; whenever the running sum becomes negative, throw it away and start fresh, because a negative start can only make what follows smaller.

    The naive approach (and why it's slow)

    Try every start and every end, summing as you go: O(n²). With 100,000 elements, that's about 5 billion additions.

    The key insight: a negative prefix never helps

    Walk the array and keep current: the best sum of a subarray that ends at the current element. At each new number x, there are only two options:

    • Extend the previous subarray: current + x.
    • Start fresh at x: just x.

    Extending is worse exactly when current is negative: adding a negative number to x only makes it smaller. So:

    text
    current = max(x, current + x)      best sum ending here
    best    = max(best, current)       best sum seen anywhere

    This is called Kadane's algorithm.

    Step by step

    nums = [-2, 1, -3, 4, -1, 2, 1, -5, 4]. Start both at nums[0] = -2:

    xExtend (current + x)Start fresh (x)currentbest
    -2(start)-2-2
    1-1111
    -3-2-3-21
    42444
    -13-134
    25255
    16166
    -51-516
    45456

    Answer: 6 (the subarray [4, -1, 2, 1], which started fresh at the 4).

    The code

    The reference solution is below, with comments on every important line.

    How fast is it?

    • Time: O(n). One pass.
    • Memory: O(1). Two variables.

    Common mistakes

    • Starting best (or current) at 0. On [-3, -1, -2] you'd return 0, which isn't the sum of any non-empty subarray. Start with nums[0].
    • Resetting current to 0 when it goes negative, then forgetting to compare. max(x, current + x) handles it in one line.
    • Returning current instead of best. The best subarray might have ended earlier.

    Going deeper

    • Greedy or DP? Both. current is a one-variable DP ("best sum ending here", like Maximum Product Subarray), and "drop a negative prefix" is a greedy choice that the DP proves is safe. That's why it's often filed under Greedy.
    • To return the subarray itself, also remember where the current run started and where the best one ended.

    Reference solution

    js
    /**
     * @param {number[]} nums
     * @return {number}
     */
    export default function maxSubArray(nums) {
      let current = nums[0] // best sum of a subarray ENDING at the current element
      let best = nums[0] // best sum anywhere (not 0: every number may be negative)
      for (let i = 1; i < nums.length; i++) {
        // Start fresh at nums[i], or extend: extending only loses when current is negative.
        current = Math.max(nums[i], current + nums[i])
        best = Math.max(best, current)
      }
      return best
    }
    ts
    export default function maxSubArray(nums: number[]): number {
      let current = nums[0] // best sum of a subarray ENDING at the current element
      let best = nums[0] // best sum anywhere (not 0: every number may be negative)
      for (let i = 1; i < nums.length; i++) {
        // Start fresh at nums[i], or extend: extending only loses when current is negative.
        current = Math.max(nums[i], current + nums[i])
        best = Math.max(best, current)
      }
      return best
    }
    python
    def max_sub_array(nums: list[int]) -> int:
        # current: best sum of a subarray ENDING at the current element.
        # best: best sum anywhere (not 0: every number may be negative).
        current = best = nums[0]
        for x in nums[1:]:
            # Start fresh at x, or extend: extending only loses when current is negative.
            current = max(x, current + x)
            best = max(best, current)
        return best