Maximum Subarray

MediumGreedy

Given an array of integers nums, find the non-empty run of neighbouring values with the largest sum, and return that sum.

Examples

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

5 + (-1) + 2 = 6.

Example 2
Input:  nums = [-7, -2, -9]
Output: -2

The run cannot be empty, so the best is the single value -2.

Constraints

  • 1 ≤ nums.length ≤ 10⁵
  • -10⁴ ≤ nums[i] ≤ 10⁴

Stuck?

Hint 1

Walk left to right. A run ending here either extends the best run ending one step earlier or starts fresh at this value: whichever is bigger.

Hint 2

Start fresh exactly when the running sum has gone below zero. Keep the best sum seen, and start it at the first value, not at 0, since every value may be negative.

Still stuck? Read the solution

JavaScript
Loading the editor

Run checks your code against the 2 examples. Submit checks all 10 tests, most of them hidden.

Ctrl + Enter runs, and adding Shift submits. On a Mac, use ⌘.

blur