Skip to content

Maximum Subarray

Given an integer array nums, find the subarray with the largest sum, and return its sum.

A subarray is a contiguous non-empty sequence of elements within an array.

Example 1:

Input: nums = [-2,1,-3,4,-1,2,1,-5,4]
Output: 6
Explanation: The subarray [4,-1,2,1] has the largest sum 6.

Example 2:

Input: nums = [1]
Output: 1
Explanation: The subarray [1] has the largest sum 1.

Example 3:

Input: nums = [5,4,-1,7,8]
Output: 23
Explanation: The subarray [5,4,-1,7,8] has the largest sum 23.

Constraints:

  • 1≤1 \le nums.length ≤105\le 10^5
  • −104≤-10^4 \le nums[i] ≤104\le 10^4

Follow-up: If you have figured out the O(n)O(n) solution, try coding another solution using the divide and conquer approach, which is more subtle.

Intuition

Let cur be the largest sum of a subarray that ends at the current index. A subarray ending at index i is either nums[i] alone or a subarray ending at i - 1 extended by nums[i], so

cur = max(nums[i], cur + nums[i]).

In words: if the best sum ending just before i is negative, it can only hurt, so drop it and start fresh at nums[i]. The answer is the largest cur seen over all end positions. Checking every subarray would be O(n2)O(n^2); this needs one pass.

Algorithm

  1. best = nums[0], cur = 0.
  2. For each x in nums: cur = max(x, cur + x), then best = max(best, cur).
  3. Return best.

Walkthrough on Example 1 (blue is the current element, green the subarray behind best):

  1. Kadane's algorithm on [-2,1,-3,4,-1,2,1,-5,4], step 1 of 11
  2. Kadane's algorithm on [-2,1,-3,4,-1,2,1,-5,4], step 2 of 11
  3. Kadane's algorithm on [-2,1,-3,4,-1,2,1,-5,4], step 3 of 11
  4. Kadane's algorithm on [-2,1,-3,4,-1,2,1,-5,4], step 4 of 11
  5. Kadane's algorithm on [-2,1,-3,4,-1,2,1,-5,4], step 5 of 11
  6. Kadane's algorithm on [-2,1,-3,4,-1,2,1,-5,4], step 6 of 11
  7. Kadane's algorithm on [-2,1,-3,4,-1,2,1,-5,4], step 7 of 11
  8. Kadane's algorithm on [-2,1,-3,4,-1,2,1,-5,4], step 8 of 11
  9. Kadane's algorithm on [-2,1,-3,4,-1,2,1,-5,4], step 9 of 11
  10. Kadane's algorithm on [-2,1,-3,4,-1,2,1,-5,4], step 10 of 11
  11. Kadane's algorithm on [-2,1,-3,4,-1,2,1,-5,4], step 11 of 11
11 steps. Swipe or scroll to move between them.

Complexity

  • Time: O(n)O(n) — one pass.
  • Space: O(1)O(1).

Approach 2: Divide and conquer (follow-up)

Section titled “Approach 2: Divide and conquer (follow-up)”

Intuition

Split the range at the middle m. The best subarray lies entirely in the left half, entirely in the right half, or crosses the middle — and a crossing subarray is a best suffix of the left half glued to a best prefix of the right half. If every recursive call returns four numbers for its range,

FieldMeaningCombine rule
totalsum of the whole rangeL.total + R.total
prefixbest sum of a prefixmax(L.prefix, L.total + R.prefix)
suffixbest sum of a suffixmax(R.suffix, R.total + L.suffix)
bestbest sum of any subarraymax(L.best, R.best, L.suffix + R.prefix)

then each combine step is O(1)O(1), and no linear scan for the crossing case is needed.

Algorithm

  1. solve(l, r): for a single element all four fields equal nums[l].
  2. Otherwise recurse on [l, m] and [m + 1, r] and combine with the rules above.
  3. Return solve(0, n - 1).best.

Complexity

  • Time: O(n)O(n) — the recursion tree has 2n - 1 nodes with O(1)O(1) work each. (The common textbook version that rescans the crossing sum at every level is O(nlog⁡n)O(n \log n).)
  • Space: O(log⁡n)O(\log n) — recursion depth.
  • All negative numbers, e.g. [-3,-1,-2]: Kadane’s cur restarts at every element, and best becomes the largest single element -1; the divide-and-conquer leaves start from real elements, so it also never returns an empty-subarray 0.
  • Single element (Example 2): Kadane runs one iteration; solve hits the base case immediately.
  • Overflow: the largest possible sum is 105⋅104=10910^5 \cdot 10^4 = 10^9, which fits in an int.

Think before you peek

Work out an approach on your own first — the explanation will still be here when you want it.

Approach 1: Kadane's algorithm
class Solution {
public:
int maxSubArray(vector<int>& nums) {
int best = nums[0], cur = 0;
for (int x : nums) {
cur = max(x, cur + x);
best = max(best, cur);
}
return best;
}
};
Approach 1: Kadane's algorithm
class Solution {
public int maxSubArray(int[] nums) {
int best = nums[0], cur = 0;
for (int x : nums) {
cur = Math.max(x, cur + x);
best = Math.max(best, cur);
}
return best;
}
}
Approach 1: Kadane's algorithm
class Solution:
def maxSubArray(self, nums: list[int]) -> int:
best, cur = nums[0], 0
for x in nums:
cur = max(x, cur + x)
best = max(best, cur)
return best
Approach 2: Divide and conquer
class Solution {
struct Info {
int total, prefix, suffix, best;
};
Info solve(const vector<int>& a, int l, int r) {
if (l == r) return {a[l], a[l], a[l], a[l]};
int m = l + (r - l) / 2;
Info L = solve(a, l, m), R = solve(a, m + 1, r);
return {L.total + R.total,
max(L.prefix, L.total + R.prefix),
max(R.suffix, R.total + L.suffix),
max({L.best, R.best, L.suffix + R.prefix})};
}
public:
int maxSubArray(vector<int>& nums) {
return solve(nums, 0, (int)nums.size() - 1).best;
}
};
Approach 2: Divide and conquer
class Solution {
private record Info(int total, int prefix, int suffix, int best) {}
private Info solve(int[] a, int l, int r) {
if (l == r) return new Info(a[l], a[l], a[l], a[l]);
int m = l + (r - l) / 2;
Info L = solve(a, l, m), R = solve(a, m + 1, r);
return new Info(L.total() + R.total(),
Math.max(L.prefix(), L.total() + R.prefix()),
Math.max(R.suffix(), R.total() + L.suffix()),
Math.max(Math.max(L.best(), R.best()), L.suffix() + R.prefix()));
}
public int maxSubArray(int[] nums) {
return solve(nums, 0, nums.length - 1).best();
}
}
Approach 2: Divide and conquer
class Solution:
def maxSubArray(self, nums: list[int]) -> int:
# Returns (total, prefix, suffix, best) for nums[l..r].
def solve(l: int, r: int) -> tuple[int, int, int, int]:
if l == r:
x = nums[l]
return x, x, x, x
m = (l + r) // 2
lt, lp, ls, lb = solve(l, m)
rt, rp, rs, rb = solve(m + 1, r)
return (lt + rt,
max(lp, lt + rp),
max(rs, rt + ls),
max(lb, rb, ls + rp))
return solve(0, len(nums) - 1)[3]

Give it a try first

Attempt the problem on LeetCode — the code will still be here.