CodingNodes / Greedy / Maximum Subarray System design Space play · ←→ step · R restart

Problem

Given an integer array nums, look at every contiguous run of one or more elements and add it up.

Return the largest sum any such run can have. Negative numbers are allowed, so the best run may be a single element.

Constraints

  • 1 ≤ nums.length ≤ 100000
  • −10000 ≤ nums[i] ≤ 10000
  • Every sum fits comfortably in a 32-bit int

Examples: pick one to animate

Solutions

TimeO(n) SpaceO(1)

Time: One pass over the array with constant work per element.

Space: Only cur and best are stored.

Let cur be the best sum of a run that ends at the current element. A run ending here either extends the run ending at the previous element, or starts fresh at this element; extending only helps when the previous run is positive. Keep best as the largest cur ever seen.