InterviewPrepKit

Home / Coding / Greedy

Maximum Subarray

medium Original ↗
Solving tips
  • This is Kadane's algorithm: keep a rolling cur = max(nums[i], cur + nums[i]) — restart whenever the running prefix turns negative since it can only drag future sums down.
  • Track best = max(best, cur) separately as you go.
  • Seed both best and cur from nums[0], never 0, so the all-negative case correctly returns the least-negative element.
  • Target O(n) time and O(1) space; the divide-and-conquer O(n log n) crossing-sum variant is a classic follow-up.

Problem

Given an integer array nums, find the contiguous subarray (containing at least one element) with the largest sum, and return that sum. The subarray must be a single unbroken run of elements.

Examples

  • nums = [-2,1,-3,4,-1,2,1,-5,4]6 — the subarray [4,-1,2,1] sums to 6, the best possible.
  • nums = [1]1 — the only subarray.
  • nums = [-3,-1,-2]-1 — all negative, so the best is the single largest element -1 (a subarray must be non-empty).

Constraints

  • 1 <= len(nums) <= 10^5
  • -10^4 <= nums[i] <= 10^4

O(n) is expected. The all-negative case is the classic edge case: you must return the least-bad single element, not 0.

Think about it first

Hint 1 Scan left to right and keep a running sum of the "current best subarray ending here." When would extending that run to the current element be worse than starting fresh at the current element?
Hint 2 If the running sum has gone negative, any subarray that carries it forward is dragged down. Dropping that negative prefix and restarting at the current element is never worse.
Hint 3 This is Kadane's algorithm: cur = max(nums[i], cur + nums[i]), and track the best cur ever seen. Initialize both from nums[0] so the all-negative case is handled.
Your workspace Not runnable by design — this is your interview scratchpad. Saved on this device.