LeetCode 53 Max Subarray Sum: From Brute Force to Kadane, Divide & Conquer & Segment Tree
This article provides a comprehensive guide to LeetCode 53 Maximum Subarray Sum, covering brute force, greedy, Kadane's algorithm (DP), divide and conquer, and segment tree solutions, with detailed derivations, code implementations, common pitfalls, and interview follow-up variants.
Reading font

Problem Clarification: Three Keywords
Given an integer array nums, find a contiguous subarray (at least one element) with the largest sum. Three keywords define the constraints:
Contiguous – subarray, not subsequence; cannot sort or skip elements.
Non-empty – must pick at least one element; all-negative arrays cannot return 0.
Max sum – only the value is asked, but follow-ups often require returning the interval.
Example: nums = [-2, 1, -3, 4, -1, 2, 1, -5, 4] → max sum is 6 from subarray [4, -1, 2, 1].
Solution Evolution Overview
Interview rhythm: start with brute force to show understanding, then optimize to demonstrate analysis, finally present optimal solution. Evolution path: Brute force O(n²) → Greedy O(n) → Kadane/DP O(n) O(1) → Divide & Conquer O(n log n) → Segment Tree O(n) build + O(log n) query.
Brute Force Enumeration
Enumerate all start/end indices, accumulate sum, track maximum. Optimized from O(n³) to O(n²) by fixing start and extending end while accumulating.
// O(n²) – just for understanding, don't stay here in interview
public int maxSubArrayBruteForce(int[] nums) {
int result = Integer.MIN_VALUE;
for (int i = 0; i < nums.length; i++) {
int count = 0;
for (int j = i; j < nums.length; j++) {
count += nums[j];
result = Math.max(result, count);
}
}
return result;
}Greedy Approach: Discard Negative Accumulation
Core strategy: When the running sum becomes non-positive, discard it and restart from the next element. A negative accumulated sum only drags down future totals.
Step-by-step simulation on [-2, 1, -3, 4, -1, 2, 1, -5, 4]:
i=0, num=-2: count=-2, result=-2 → count≤0 reset to 0
i=1, num=1: count=1, result=1
i=2, num=-3: count=-2, result=1 → reset
i=3, num=4: count=4, result=4
i=4, num=-1: count=3, result=4
i=5, num=2: count=5, result=5
i=6, num=1: count=6, result=6 ✅
i=7, num=-5: count=1, result=6
i=8, num=4: count=5, result=6
Code:
public int maxSubArray(int[] nums) {
int result = Integer.MIN_VALUE; // ⚠️ must be MIN_VALUE, not 0
int count = 0;
for (int num : nums) {
count += num;
if (count > result) result = count;
if (count <= 0) count = 0; // discard when sum ≤ 0
}
return result;
}⚠️ Common Misunderstanding: Reset when cumulative sum becomes negative, not when encountering a negative number. Example [4, -1, 2] : at -1 cumulative sum is 3 (positive), so keep it; answer is 5 not 4.
Kadane Algorithm (Dynamic Programming): Standard Interview Answer
State Definition: Why "Ending at i"?
Define dp[i] = maximum sum of contiguous subarray ending at nums[i] . This forces inclusion of nums[i], guaranteeing continuity between adjacent states. Defining as "max among first i elements" breaks transition because the optimal subarray may not include nums[i].
State Transition: Two Choices at Each Position
dp[i] = max(dp[i-1] + nums[i], nums[i])
───────────────── ───────
Option A: extend Option B: restartExtend when dp[i-1] > 0 (positive asset).
Restart when dp[i-1] ≤ 0 (liability).
Final answer is max over all dp[i] , not dp[n-1] (common mistake).
Full Derivation Walkthrough
Running the example yields dp = [-2, 1, -2, 4, 3, 5, 6, 1, 5], global max = 6 at index 6, corresponding to subarray [4, -1, 2, 1].
Space-Optimized Code (Rolling Variable)
class Solution {
public int maxSubArray(int[] nums) {
if (nums == null || nums.length == 0) {
throw new IllegalArgumentException("Array cannot be empty");
}
int cur = nums[0]; // max subarray ending at current position, ⚠️ init with nums[0]
int maxAns = nums[0]; // global maximum
for (int i = 1; i < nums.length; i++) {
cur = Math.max(nums[i], cur + nums[i]); // extend or restart
maxAns = Math.max(maxAns, cur); // refresh global max every step
}
return maxAns;
}
}Key Interview Talking Points: Initialize with nums[0] , not 0 – otherwise all-negative arrays (e.g., [-3, -1, -2] ) incorrectly return 0; correct answer is -1. Space O(1) – only two variables; dp[i] depends only on dp[i-1] , classic rolling array. Two Math.max serve distinct roles: local decision (extend vs restart) and global recording; order matters. Time O(n) is theoretical lower bound – must inspect each element at least once.
Greedy vs DP: Equivalent Perspectives
Greedy: count ≤ 0 → reset. DP: dp[i] = max(dp[i-1]+nums[i], nums[i]). When dp[i-1] < 0, choosing nums[i] is exactly resetting. Both are O(n) time, O(1) space. Additional insight: prefix sum formulation ans = max(prefix[i] - minPrefixBefore) – current prefix minus minimum previous prefix.
Advanced: Return Subarray Indices (Interval Follow-up)
Track start when restarting, lock [bestL, bestR] when global max updates. Mnemonic: "Restart records start, refresh locks interval."
public int[] maxSubArrayRange(int[] nums) {
int cur = nums[0], ans = nums[0];
int start = 0, bestL = 0, bestR = 0;
for (int i = 1; i < nums.length; i++) {
if (cur < 0) { cur = nums[i]; start = i; }
else { cur += nums[i]; }
if (cur > ans) { ans = cur; bestL = start; bestR = i; }
}
return Arrays.copyOfRange(nums, bestL, bestR + 1);
}Divide & Conquer: Extensibility Over Speed
Core Idea
Split array at mid. Maximum subarray lies in one of three regions: entirely left, entirely right, or crossing mid. Recursively solve left/right, compute crossing sum by expanding from mid outward to find max suffix on left and max prefix on right.
Implementation
class Solution {
public int maxSubArray(int[] nums) {
return divide(nums, 0, nums.length - 1);
}
private int divide(int[] nums, int left, int right) {
if (left == right) return nums[left];
int mid = left + (right - left) / 2; // overflow-safe
int leftMax = divide(nums, left, mid);
int rightMax = divide(nums, mid + 1, right);
int crossMax = crossSum(nums, left, mid, right);
return Math.max(Math.max(leftMax, rightMax), crossMax);
}
private int crossSum(int[] nums, int left, int mid, int right) {
int leftSum = Integer.MIN_VALUE, sum = 0;
for (int i = mid; i >= left; i--) { sum += nums[i]; leftSum = Math.max(leftSum, sum); }
int rightSum = Integer.MIN_VALUE; sum = 0;
for (int i = mid + 1; i <= right; i++) { sum += nums[i]; rightSum = Math.max(rightSum, sum); }
return leftSum + rightSum;
}
}Time O(n log n), space O(log n) recursion stack. Real value is extensibility: each segment maintains a four-tuple [sum, lmax, rmax, max] (total sum, max prefix, max suffix, max subarray). Merge rule: max = max(left.max, right.max, left.rmax + right.lmax). This tuple is associative, enabling segment trees, parallel computation, and MapReduce.
Four-Tuple Merge Code
// Four-tuple: [lSum (max prefix), rSum (max suffix), iSum (total), mSum (max subarray)]
private int[] merge(int[] a, int[] b) {
return new int[]{
Math.max(a[0], a[2] + b[0]), // max prefix
Math.max(b[1], b[2] + a[1]), // max suffix
a[2] + b[2], // total sum
Math.max(Math.max(a[3], b[3]), a[1] + b[0]) // max subarray
};
}
public int maxSubArrayDC(int[] nums) { return solve(nums, 0, nums.length - 1)[3]; }
private int[] solve(int[] nums, int l, int r) {
if (l == r) return new int[]{nums[l], nums[l], nums[l], nums[l]};
int mid = (l + r) >> 1;
return merge(solve(nums, l, mid), solve(nums, mid + 1, r));
}Interview talking point: "Divide & conquer is slower than Kadane, but its four-tuple merge naturally extends to segment trees for dynamic updates and distributed queries. Kadane itself is an O(1) online algorithm for streaming data."
Complexity Comparison
Brute Force : O(n²)/O(n³) time, O(1) space – only for verification.
Prefix Sum + Traversal : O(n²) time, O(n) space – correct idea, not optimized.
Kadane / DP : O(n) time, O(1) space – single pass, rolling variable, interview standard .
Divide & Conquer : O(n log n) time, O(log n) space – shows breadth, strong extensibility.
Segment Tree : O(n) build + O(log n) query, O(n) space – dynamic updates + multiple range queries.
8 High-Frequency Pitfalls
All-negative array – returning 0; fix: init cur = ans = nums[0].
Wrong answer position – returning dp[n-1]; fix: update global max every step.
Unclear state definition – defining dp[i] as "max of first i"; fix: define as "ending at i".
Subarray vs subsequence confusion – wanting to sort/pick positives; fix: continuity forces DP/prefix sum.
Reset semantics – thinking "reset on negative number"; fix: reset when cumulative sum ≤ 0.
Restart missing current value – writing if(cur<0) cur=0; fix: cur = max(nums[i], cur+nums[i]).
Divide mid overflow – (left+right)/2; fix: left + (right-left)/2.
Integer overflow – large sums; fix: use long in engineering, declare range in interview.
Also, in divide & conquer crossing sum, must expand from mid outward separately for left suffix and right prefix, including mid itself.
Interview Follow-up Variants
Return subarray indices – track start on restart, lock interval on max update (see above).
Circular array max subarray sum (LeetCode 918) – max(normalMax, totalSum - minSubarraySum); special-case all-negative.
Maximum product subarray (LeetCode 152) – maintain both max and min (negative × negative = positive).
Length at least K – prefix sum + monotonic queue.
Dynamic update + query – segment tree with four-tuple per node.
2D maximum submatrix – enumerate top/bottom boundaries O(n²), compress columns to 1D, apply Kadane O(n³) total.
The "dp state = ending at i" pattern solves a whole family: 152, 918, max submatrix, etc. – one problem mastered, hundreds understood .
Interview Script & Mnemonics
Self-check levels: brute force ✅ → greedy/DP ✅ → all-negative boundary ✅✅ → know "Kadane" name ✅✅✅ → divide & conquer four-tuple & segment tree ✅✅✅✅.
Answer rhythm: 1) Restate constraints (contiguous, non-empty). 2) Present brute force O(n²), say "need better". 3) Explain "extend or restart" decision before coding. 4) Proactively mention space optimization and all-negative trap. 5) Close with divide & conquer and segment tree extensions.
Mnemonic: "Positive is asset, negative is liability; liability → bankrupt restart; track peak wealth throughout."
Poetic version: "Negative prefix → break up; positive current → hold hands; rolling record of peak; linear pass → answer in hand."
Conclusion
The soul of this problem: "Positive prefix → extend, negative → restart" plus "global max updated every step". Master these two sentences and Kadane becomes your Swiss Army knife. Add the four-tuple merge for divide & conquer, and you can climb to segment trees.
Practice: implement LeetCode 53 from memory, then immediately do 152 (product) and 918 (circular) – they form a combo that proves true mastery.
For questions about attribution, corrections or content rights, please contactand we will review it promptly.