Problem
Section titled “Problem”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: 6Explanation: The subarray [4,-1,2,1] has the largest sum 6.Example 2:
Input: nums = [1]Output: 1Explanation: The subarray [1] has the largest sum 1.Example 3:
Input: nums = [5,4,-1,7,8]Output: 23Explanation: The subarray [5,4,-1,7,8] has the largest sum 23.Constraints:
-
nums.length -
nums[i]
Follow-up: If you have figured out the solution, try coding another solution using the divide and conquer approach, which is more subtle.
Solution approach
Section titled “Solution approach”Approach 1: Kadane’s algorithm
Section titled “Approach 1: Kadane’s algorithm”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 ; this needs one pass.
Algorithm
best = nums[0],cur = 0.- For each
xinnums:cur = max(x, cur + x), thenbest = max(best, cur). - Return
best.
Walkthrough on Example 1 (blue is the current element, green the subarray behind best):
Complexity
- Time: — one pass.
- Space: .
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,
| Field | Meaning | Combine rule |
|---|---|---|
total | sum of the whole range | L.total + R.total |
prefix | best sum of a prefix | max(L.prefix, L.total + R.prefix) |
suffix | best sum of a suffix | max(R.suffix, R.total + L.suffix) |
best | best sum of any subarray | max(L.best, R.best, L.suffix + R.prefix) |
then each combine step is , and no linear scan for the crossing case is needed.
Algorithm
solve(l, r): for a single element all four fields equalnums[l].- Otherwise recurse on
[l, m]and[m + 1, r]and combine with the rules above. - Return
solve(0, n - 1).best.
Complexity
- Time: — the recursion tree has
2n - 1nodes with work each. (The common textbook version that rescans the crossing sum at every level is .) - Space: — recursion depth.
Edge cases
Section titled “Edge cases”- All negative numbers, e.g.
[-3,-1,-2]: Kadane’scurrestarts at every element, andbestbecomes the largest single element-1; the divide-and-conquer leaves start from real elements, so it also never returns an empty-subarray0. - Single element (Example 2): Kadane runs one iteration;
solvehits the base case immediately. - Overflow: the largest possible sum is , 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.
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; }};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; }}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 bestclass 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; }};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(); }}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.
![Kadane's algorithm on [-2,1,-3,4,-1,2,1,-5,4], step 1 of 11](/CodePrime/img/codes/maximum-subarray/kadane/01.webp)
![Kadane's algorithm on [-2,1,-3,4,-1,2,1,-5,4], step 2 of 11](/CodePrime/img/codes/maximum-subarray/kadane/02.webp)
![Kadane's algorithm on [-2,1,-3,4,-1,2,1,-5,4], step 3 of 11](/CodePrime/img/codes/maximum-subarray/kadane/03.webp)
![Kadane's algorithm on [-2,1,-3,4,-1,2,1,-5,4], step 4 of 11](/CodePrime/img/codes/maximum-subarray/kadane/04.webp)
![Kadane's algorithm on [-2,1,-3,4,-1,2,1,-5,4], step 5 of 11](/CodePrime/img/codes/maximum-subarray/kadane/05.webp)
![Kadane's algorithm on [-2,1,-3,4,-1,2,1,-5,4], step 6 of 11](/CodePrime/img/codes/maximum-subarray/kadane/06.webp)
![Kadane's algorithm on [-2,1,-3,4,-1,2,1,-5,4], step 7 of 11](/CodePrime/img/codes/maximum-subarray/kadane/07.webp)
![Kadane's algorithm on [-2,1,-3,4,-1,2,1,-5,4], step 8 of 11](/CodePrime/img/codes/maximum-subarray/kadane/08.webp)
![Kadane's algorithm on [-2,1,-3,4,-1,2,1,-5,4], step 9 of 11](/CodePrime/img/codes/maximum-subarray/kadane/09.webp)
![Kadane's algorithm on [-2,1,-3,4,-1,2,1,-5,4], step 10 of 11](/CodePrime/img/codes/maximum-subarray/kadane/10.webp)
![Kadane's algorithm on [-2,1,-3,4,-1,2,1,-5,4], step 11 of 11](/CodePrime/img/codes/maximum-subarray/kadane/11.webp)