Maximum Subarray Sum in Java (Leetcode 53): DP Approach
I had already solved Maximum Subarray on LeetCode once before, but going back to it with Dynamic Programming makes the logic much easier to trust when you are under interview pressure. Instead of memorizing a trick, you build a small rule at every index and let the array do the work.
Below, I walk through the DP approach step by step—first with a live simulator so you can watch dp[i] update at every element, then with the full Java code using a dp array, and finally the two-variable version that saves memory.
Video Walkthrough
If you prefer watching me trace the iterations and submit the code on LeetCode, here is the video explanation:
1. What the Problem Actually Asks
LeetCode 53 gives you an integer array nums containing positive numbers, negative numbers, and zeros. You need to find a contiguous subarray that gives the highest possible sum and return that sum.
- The elements must be contiguous—you cannot skip over numbers and pick pieces from different parts of the array.
- The subarray cannot be empty; at least one number must be included (this matters a lot when every number is negative).
- You only return the largest sum, not the subarray itself.
Sample Inputs
Output: 6
Why: Taking [4, -1, 2, 1] gives 4 - 1 + 2 + 1 = 6.
Output: 23
Why: Even with -1 in the middle, keeping the whole array [5, 4, -1, 7, 8] adds up to 23.
Why Just Avoiding Negatives Fails
When I first looked at problems like this, my instinct was to stop a subarray the moment a negative number showed up. Try that on [4, -1, 2, 1] and you immediately get the wrong answer: stopping at -1 leaves you with 4 on the left or 3 on the right, missing 6 altogether.
A negative number is only bad if the entire running total before it drags your new number down. As long as the previous sum is positive, it still helps you—even if you dipped slightly along the way.
Before jumping into the Java code, click through the simulator below. Watch what happens to dp[i] when the previous total is negative versus when it is positive.
2. Setting Up the DP State
The whole solution depends on defining dp[i] properly. Here, dp[i] stores the largest subarray sum you can make that ends specifically at index i.
Once you fix the ending point at i, there are only two ways that subarray can look:
- Join the previous subarray: add the current number to whatever best sum ended at
i - 1, which givesnums[i] + dp[i - 1]. - Start over at
i: ignore everything before indexiand just takenums[i]on its own.
At each index, we simply pick the larger of the two:
One detail tripped me up the first time I wrote this: unlike problems like Climbing Stairs or House Robber, the answer is not always sitting in dp[n - 1]. The best subarray might finish halfway through the array, before a few big negative numbers at the end pull dp[i] down. That is why we keep a separate max variable and update it on every iteration.
- At index
0, there is nothing to the left, sodp[0] = nums[0]. - Set
max = nums[0]before the loop starts, then updatemax = Math.max(dp[i], max)as you go.
3. Tracing an Example by Hand
Let's trace nums = [-2, 1, -3, 4, -1, 2, 1, -5, 4] from start to finish so you can see where the subarray resets and where it keeps growing:
| Index (i) | nums[i] | Start Fresh (nums[i]) | Extend (nums[i] + dp[i-1]) | dp[i] | max so far |
|---|---|---|---|---|---|
| 0 | -2 | -2 (Base case) | — | -2 | -2 |
| 1 | 1 | 1 | 1 + (-2) = -1 | 1 | 1 |
| 2 | -3 | -3 | -3 + 1 = -2 | -2 | 1 |
| 3 | 4 | 4 | 4 + (-2) = 2 | 4 | 4 |
| 4 | -1 | -1 | -1 + 4 = 3 | 3 | 4 |
| 5 | 2 | 2 | 2 + 3 = 5 | 5 | 5 |
| 6 | 1 | 1 | 1 + 5 = 6 | 6 | 6 |
| 7 | -5 | -5 | -5 + 6 = 1 | 1 | 6 |
| 8 | 4 | 4 | 4 + 1 = 5 | 5 | 6 |
At index 3, carrying over dp[2] = -2 would drop 4 down to 2, so the algorithm drops the old run and starts over at 4. By index 6, the total hits 6. Even though the last two indices end at 5, max holds on to 6. Returned result: 6
4. Java Solutions
Version 1: Using a DP Array (O(n) space)
This is the exact code I wrote and submitted in the video above (passing all 210 LeetCode test cases in 1 ms). Keeping the dp array makes it easy to debug and matches the recurrence word for word.
class Solution {
public int maxSubArray(int[] nums) {
int n = nums.length;
int[] dp = new int[n];
dp[0] = nums[0];
int max = nums[0];
for (int i = 1; i < n; i++) {
dp[i] = Math.max(nums[i], nums[i] + dp[i - 1]);
max = Math.max(dp[i], max);
}
return max;
}
}
Version 2: Dropping the Extra Array (O(1) space)
Once you look closely at Version 1, you notice we never read dp[i - 2] or anything older—only dp[i - 1]. That means we can replace the whole array with a single curr variable. If an interviewer asks you to optimize space, this is all you need to change (and this is actually Kadane's Algorithm in disguise):
class Solution {
public int maxSubArray(int[] nums) {
int curr = nums[0];
int max = nums[0];
for (int i = 1; i < nums.length; i++) {
curr = Math.max(nums[i], curr + nums[i]);
max = Math.max(curr, max);
}
return max;
}
}
Test Both Locally
If you want to run both versions in your local IDE and compare their outputs side by side, you can use this Main class:
import java.util.Arrays;
public class Main {
static int maxSubArrayDP(int[] nums) {
int n = nums.length;
int[] dp = new int[n];
dp[0] = nums[0];
int max = nums[0];
for (int i = 1; i < n; i++) {
dp[i] = Math.max(nums[i], nums[i] + dp[i - 1]);
max = Math.max(dp[i], max);
}
return max;
}
static int maxSubArrayConstantSpace(int[] nums) {
int curr = nums[0];
int max = nums[0];
for (int i = 1; i < nums.length; i++) {
curr = Math.max(nums[i], curr + nums[i]);
max = Math.max(curr, max);
}
return max;
}
public static void main(String[] args) {
int[][] tests = {
{-2, 1, -3, 4, -1, 2, 1, -5, 4},
{1},
{5, 4, -1, 7, 8},
{-2, -3, -1, -5},
{4, -1, 2, 1}
};
for (int[] t : tests) {
System.out.println(Arrays.toString(t)
+ " -> DP array: " + maxSubArrayDP(t)
+ ", O(1) space: " + maxSubArrayConstantSpace(t));
}
}
}
Expected output:
[1] -> DP array: 1, O(1) space: 1
[5, 4, -1, 7, 8] -> DP array: 23, O(1) space: 23
[-2, -3, -1, -5] -> DP array: -1, O(1) space: -1
[4, -1, 2, 1] -> DP array: 6, O(1) space: 6
5. Time and Space Complexity
- Time Complexity:
O(n)for both versions. We touch each element once and run twoMath.maxcomparisons. - Space Complexity:
O(n)for Version 1 because we allocateint[] dp, andO(1)for Version 2 since we only store two integers.
6. Bugs to Watch Out For & Related Problems
- Starting
maxat0: If the test case is[-2, -3, -1, -5], startingmax = 0makes your code return0instead of-1. Starting withnums[0]avoids this completely. - Returning
dp[n - 1]: Remember thatdp[n - 1]only tells you the best subarray ending at the very last element, not the best subarray overall. - Divide & Conquer follow-up: LeetCode asks if you can also solve this using divide and conquer. That approach splits the array in half recursively in
O(n log n)time, though in practice theO(n)DP version is faster and cleaner. - Next problems to try: Once you are comfortable with this pattern, try LeetCode 152 (Maximum Product Subarray) and LeetCode 918 (Maximum Sum Circular Subarray)—both build directly on this same idea.
Comments
Post a Comment