Maximum Subarray

35 min · maxSubArray()

A single rough day can be worth keeping when the stretch around it is strong enough.

Given an integer array nums, return the largest sum made by one contiguous subarray, a non-empty run of neighboring elements with no gaps.

The chosen run may contain one element or the entire array. It must not be empty, so an all-negative input returns its least-negative single value rather than 0.

Constraints

  • 1 <= nums.length <= 100_000
  • -10_000 <= nums[i] <= 10_000
  • Every possible subarray sum fits in a signed 32-bit integer.

Hints

Start with every left edge

Fix a starting index and extend the right edge one position at a time, updating the sum as you go. This gives an honest O(n²) baseline.

What must end here?

For each index i, track the best non-empty subarray that ends exactly at i. It either starts at nums[i] or extends the best ending at i - 1.

Don't default to zero

Initialize both running values from nums[0]. Starting from zero accidentally allows an empty subarray and breaks every all-negative input.

Follow-up

Can you return the start and end indices of a maximum-sum subarray while keeping O(1) extra space?

Visible cases

Examples

Example 1

ready
Input
nums = [
  -2,
  1,
  -3,
  4,
  -1,
  2,
  1,
  -5,
  4
]
Expected
6
Why
the run [4, -1, 2, 1] sums to 6

Example 2

ready
Input
nums = [
  1
]
Expected
1
Why
the only non-empty subarray contains the one value

Example 3

ready
Input
nums = [
  -3,
  -1,
  -2
]
Expected
-1
Why
empty isn't allowed, so the largest single value wins

Interview signal

Asked at

AmazonGoogleMetaBloomberg
Loading editor

Console

ready to run

Ready to run.

3 cases are queued.

Run: visible + custom · Submit: full suite