Maximum subarray sum. Compare brute force, divide and conquer, and Kadane's algorithm.
Problem
[-2, 1, -3, 4, -1, 2, 1, -5, 4] → 6 ([4, -1, 2, 1]). All-negative input returns the largest (least negative) element.
Pattern
Kadane's algorithm (DP with O(1) state): the best subarray ending at i is either nums[i] alone or nums[i] added to the best subarray ending at i − 1.
Approach 1: All subarrays with running sums (feasible, O(n²))
class MaxSubBrute {
static int max(int[] a) {
int best = Integer.MIN_VALUE;
for (int i = 0; i < a.length; i++) {
int sum = 0;
for (int j = i; j < a.length; j++) { sum += a[j]; best = Math.max(best, sum); }
}
return best;
}
}Approach 2: Divide and conquer (O(n log n))
The best subarray is in the left half, the right half, or crosses the middle.
class MaxSubDivide {
static int max(int[] a) { return solve(a, 0, a.length - 1); }
private static int solve(int[] a, int lo, int hi) {
if (lo == hi) return a[lo];
int mid = (lo + hi) >>> 1;
int leftBest = Integer.MIN_VALUE, sum = 0;
for (int i = mid; i >= lo; i--) { sum += a[i]; leftBest = Math.max(leftBest, sum); }
int rightBest = Integer.MIN_VALUE; sum = 0;
for (int i = mid + 1; i <= hi; i++) { sum += a[i]; rightBest = Math.max(rightBest, sum); }
return Math.max(leftBest + rightBest, Math.max(solve(a, lo, mid), solve(a, mid + 1, hi)));
}
}Approach 3: Kadane's algorithm, also returning the subarray (O(n), O(1)) — optimal
class MaxSubKadane {
static int[] maxWithRange(int[] a) { // {sum, start, end}
int best = a[0], current = a[0], start = 0, bestStart = 0, bestEnd = 0;
for (int i = 1; i < a.length; i++) {
if (current < 0) { current = a[i]; start = i; } // starting fresh is better
else current += a[i];
if (current > best) { best = current; bestStart = start; bestEnd = i; }
}
return new int[] {best, bestStart, bestEnd};
}
}
class MaxSubDemo {
public static void main(String[] args) {
int[] a = {-2, 1, -3, 4, -1, 2, 1, -5, 4};
System.out.println(MaxSubBrute.max(a) + " " + MaxSubDivide.max(a) + " " + java.util.Arrays.toString(MaxSubKadane.maxWithRange(a))); // 6 6 [6, 3, 6]
System.out.println(MaxSubKadane.maxWithRange(new int[] {-3, -1, -2})[0]); // -1
}
}Feasible → optimal
O(n²) → O(n log n) divide and conquer → O(n), O(1) Kadane. Kadane is also the classic example of turning a DP table into constant space.
Follow-up questions interviewers ask
Try answering each one before you open it.
Related (same pattern): maximum product subarray.
Track both the maximum and the minimum product ending at i (a negative number turns the minimum into the maximum): max = max(x, x*maxPrev, x*minPrev), min = min(x, x*maxPrev, x*minPrev). O(n), O(1).
Related (same pattern): best time to buy and sell a stock (one transaction).
Track the minimum price so far and the best price - minSoFar, which is Kadane on daily price differences. O(n), O(1).