Min Cost Climbing Stairs in Java (Leetcode 746): DP Approach
When I first moved from the classic Climbing Stairs to Min Cost Climbing Stairs, I overcomplicated it. I started wondering if I should greedily pick whichever step was cheaper right in front of me. That falls apart almost immediately. A cheap step now can easily strand you in front of a massive toll right after.
The turning point for me was framing the problem backwards: "To stand at step i, what was the cheapest possible route that could have brought me here?" Once you treat each stair as a landing pad with only two ways to reach it, the Dynamic Programming recurrence practically writes itself.
In this guide, we will break down the DP intuition visually, interact with a live step-by-step simulator, inspect the recurrence table by hand, and write clean Java solutions in both O(n) and O(1) space.
Video Walkthrough
If you prefer watching the code typed out line-by-line along with test case tracing, check out the video walkthrough below:
1. Breaking Down the Rules
In LeetCode 746, you receive an array cost where cost[i] is the fee you pay to launch yourself off step i. Once you pay that fee, you can leap forward either 1 step or 2 steps.
- Free entry: You can choose to start on step
0OR step1without paying anything to land on them. You only pay when leaving. - The finish line: The "top of the floor" is NOT index
n - 1. It is indexn(one step past the last element in the array). - No backtracking: You can only move forward (+1 or +2), meaning subproblems naturally build from left to right.
Visualizing the Staircase & The Top Floor
Here is what reaching the top looks like for an array of 3 costs [10, 15, 20]:
Notice that landing on Top can happen either with a 2-step hop from Step 1 (cost 15) or a 1-step hop from Step 2 (cost 10 + 20 = 30). The answer here is 15!
Sample Walkthroughs
Output: 15
Path: Start at index 1 (pay 15) -> leap 2 steps straight to the top (index 3). Total = 15.
Output: 6
Path: Bounce across all the 1s, jumping right over every single 100. Total = 6.
Test out your own sequences or step through the algorithm in the live visualizer below before writing the Java code.
dp[i] = min(dp[i-1] + cost[i-1], dp[i-2] + cost[i-2]) resolves the minimum cost to reach every floor.2. Defining the Recurrence Relation
To solve this cleanly, let dp[i] represent the minimum total cost required to reach step index i.
To land on step i, you can only arrive from two possible origins:
- You were at
i - 1, paidcost[i - 1], and hopped 1 step. Total cost:dp[i - 1] + cost[i - 1]. - You were at
i - 2, paidcost[i - 2], and hopped 2 steps. Total cost:dp[i - 2] + cost[i - 2].
Because we want the absolute minimum cost, we take the minimum of both choices:
dp[0] = 0: It costs 0 to stand on step 0 at the start.dp[1] = 0: It costs 0 to stand on step 1 at the start.- The top of the floor is at
n = cost.length, so our ultimate answer is simplydp[n].
3. Tracing the DP Table by Hand
Let's dry run the recurrence on cost = [10, 15, 20]. Here, n = 3, so our dp array will have size 4 (indices 0, 1, 2, 3):
| Step (i) | Option 1: From (i - 1) | Option 2: From (i - 2) | dp[i] (Minimum) | Why |
|---|---|---|---|---|
| 0 | — | — | 0 | Allowed to start directly here. |
| 1 | — | — | 0 | Allowed to start directly here. |
| 2 | dp[1] + cost[1] = 0 + 15 = 15 | dp[0] + cost[0] = 0 + 10 = 10 | 10 | Cheaper to start at step 0 and jump 2. |
| 3 (Top) | dp[2] + cost[2] = 10 + 20 = 30 | dp[1] + cost[1] = 0 + 15 = 15 | 15 | Cheaper to take index 1 straight to top! |
The loop stops at index 3, and dp[3] yields our answer: 15.
4. Java Solutions
Version 1: Full DP Array (O(n) Space)
This is the clearest way to write the solution. Creating an array of size n + 1 makes it completely transparent where the final answer lives.
class Solution {
public int minCostClimbingStairs(int[] cost) {
int n = cost.length;
int[] dp = new int[n + 1];
// Base cases: starting at index 0 or index 1 costs nothing yet
dp[0] = 0;
dp[1] = 0;
// Build up minimum costs to land on each step
for (int i = 2; i <= n; i++) {
dp[i] = Math.min(dp[i - 1] + cost[i - 1], dp[i - 2] + cost[i - 2]);
}
// The top floor is at index n
return dp[n];
}
}
Version 2: Rolling Variables (O(1) Space)
Look at the loop above: calculating dp[i] only ever requires dp[i - 1] and dp[i - 2]. We don't care about anything older. We can collapse the entire array into two variables, exactly like calculating Fibonacci numbers:
class Solution {
public int minCostClimbingStairs(int[] cost) {
int prev2 = 0; // represents dp[i - 2]
int prev1 = 0; // represents dp[i - 1]
for (int i = 2; i <= cost.length; i++) {
int current = Math.min(prev1 + cost[i - 1], prev2 + cost[i - 2]);
prev2 = prev1;
prev1 = current;
}
return prev1;
}
}
Run and Verify Locally
Drop this into your favorite IDE to run both implementations through edge cases side by side:
import java.util.Arrays;
public class Main {
static int minCostDP(int[] cost) {
int n = cost.length;
int[] dp = new int[n + 1];
dp[0] = 0;
dp[1] = 0;
for (int i = 2; i <= n; i++) {
dp[i] = Math.min(dp[i - 1] + cost[i - 1], dp[i - 2] + cost[i - 2]);
}
return dp[n];
}
static int minCostOptimized(int[] cost) {
int prev2 = 0;
int prev1 = 0;
for (int i = 2; i <= cost.length; i++) {
int current = Math.min(prev1 + cost[i - 1], prev2 + cost[i - 2]);
prev2 = prev1;
prev1 = current;
}
return prev1;
}
public static void main(String[] args) {
int[][] testCases = {
{10, 15, 20},
{1, 100, 1, 1, 1, 100, 1, 1, 100, 1},
{0, 0, 0, 1},
{2, 1}
};
for (int[] cost : testCases) {
System.out.println(Arrays.toString(cost)
+ " -> DP: " + minCostDP(cost)
+ " | O(1) Space: " + minCostOptimized(cost));
}
}
}
Console Output:
[1, 100, 1, 1, 1, 100, 1, 1, 100, 1] -> DP: 6 | O(1) Space: 6
[0, 0, 0, 1] -> DP: 0 | O(1) Space: 0
[2, 1] -> DP: 1 | O(1) Space: 1
5. Complexity Analysis
- Time Complexity:
O(n). We traverse the array once from index2ton, doing constant-timeMath.min()operations at every step. - Space Complexity:
O(n)for the DP array version.O(1)for the rolling variable version because we only preserve two integer states.
6. Common Mistakes & Related Problems
- Thinking step
n - 1is the top: Landing on the final index is not the goal; you must leap past it onto the floor leveln. - Greedy pitfall: Selecting
min(cost[0], cost[1])as your first step and locking it in is tempting, but a cheap first step might force you into expensive downstream paths later. DP solves this by checking all combinations smoothly. - Recommended Next Problems:
- LeetCode 70 (Climbing Stairs): The simpler precursor counting total permutations instead of min cost.
- LeetCode 198 (House Robber): Uses the exact same two-choice recurrence concept, but asking for maximum non-adjacent value.
- LeetCode 55 (Jump Game): Shifting from cost accumulation to reachability.
Comments
Post a Comment