Maximum Subarray
Find the contiguous subarray with the largest sum using Kadane's algorithm in O(n) time.
01The problem
Given an integer array nums, find the contiguous subarray (containing at least one number) which has the largest sum and return its sum.
02How to spot it
- "Contiguous subarray" with "maximum sum".
- If a running prefix sum drops below 0, continuing that subarray can only harm future elements; restarting a fresh subarray at the current number is always superior.
- Classic Kadane's algorithm.
03Pseudocode
cur = best = nums[0]
for i from 1:
cur = max(nums[i], cur + nums[i])
best = max(best, cur)
return best04Watch it work
nums
best sum
-2
Start Kadane's algorithm: cur = -2, best = -2.
Pseudocode
- cur = best = nums[0]
- for i from 1:
- cur = max(nums[i], cur + nums[i])
- best = max(best, cur)
- return best
Variables
- cur
- -2
- best
- -2
05Step-by-step dry run
For nums = [-2, 1, -3, 4, -1, 2, 1, -5, 4]:
cur = -2,best = -2.i = 1 (1):cur = max(1, -2 + 1) = 1,best = 1.i = 2 (-3):cur = max(-3, 1 - 3) = -2,best = 1.i = 3 (4):cur = max(4, -2 + 4) = 4(restart!),best = 4.i = 4 (-1):cur = max(-1, 4 - 1) = 3,best = 4.i = 5 (2):cur = max(2, 3 + 2) = 5,best = 5.i = 6 (1):cur = max(1, 5 + 1) = 6,best = 6.i = 7 (-5):cur = max(-5, 6 - 5) = 1,best = 6.i = 8 (4):cur = max(4, 1 + 4) = 5,best = 6.- Return
best = 6(subarray[4, -1, 2, 1]).
06Java solution
public class Main {
public static int maxSubArray(int[] nums) {
int cur = nums[0], best = nums[0];
for (int i = 1; i < nums.length; i++) {
cur = Math.max(nums[i], cur + nums[i]);
best = Math.max(best, cur);
}
return best;
}
public static void main(String[] args) {
System.out.println(maxSubArray(new int[]{-2, 1, -3, 4, -1, 2, 1, -5, 4}));
System.out.println(maxSubArray(new int[]{5, 4, -1, 7, 8}));
System.out.println(maxSubArray(new int[]{-1}));
}
}6 23 -1
07Why it works
At each position i, a subarray ending at i must either extend the subarray ending at i - 1 (summing cur + nums[i]) or start fresh at nums[i]. If cur < 0, adding it to nums[i] yields a sum smaller than nums[i] alone, so dropping the negative prefix is always optimal. Tracking the running maximum over all positions guarantees the global peak subarray sum.
08Time and space
- Time complexity:
O(n)single linear scan over the array. - Space complexity:
O(1)using two integer variables.
09Edge cases
- All negative numbers (e.g.
[-5, -2, -8]):curandbestboth initialize tonums[0]; algorithm correctly picks the single least-negative number (-2). - Single element: Loop does not execute; returns
nums[0].
10Common mistakes
- Initializing
best = 0: Fails when all array values are negative; initialize tonums[0]. - Assuming sliding window works with negative numbers: Window contraction criteria break when negative numbers can increase future sums; Kadane's DP is required.
11Other approaches
- Divide and Conquer: Can solve in
O(n log n)time by dividing array in half and finding max across the midpoint, but Kadane'sO(n)is simpler and faster.
12In the interview
- State Kadane's algorithm immediately: "At each index, I either extend the existing subarray or restart fresh if the previous sum is negative."
- Highlight initialization:
cur = best = nums[0]to handle arrays of all negative numbers correctly.
13Quiz
Why must best be initialized to nums[0] instead of 0?
- (Recommended) To correctly handle arrays where all elements are negative
- Because Java arrays must be indexed at 0
- Because 0 is not a valid sum
- To prevent division by zero
Answer: To correctly handle arrays where all elements are negative. If all numbers are negative (e.g. [-3, -1, -5]), the maximum sum is -1. Initializing to 0 would mistakenly return 0.
14Solve it yourself
Open LeetCode #53 and submit Kadane's algorithm.