Minimum Cost to Reach the Top
This problem is about climbing past the end of a staircase while paying as little total cost as possible. Each position in costs tells you how much you pay when you land on that step, and from any step you can move forward by either 1 or 2 steps.
Because you can jump over steps, the cheapest path is not always the one that uses the fewest moves. Sometimes paying one medium cost lets you avoid two expensive landings later. So the goal is to minimize the full path cost, not just make a locally cheap move.
For example, if costs = [10,15,20], the answer is 15. Landing on the step with cost 15 and then moving past the end is cheaper than paths that include 10 and 20. If costs = [1,100,1,1,1,100,1,1,100,1], the answer is 6 because a good path lands mostly on the steps with cost 1.
So the task is to find the minimum total cost needed to move beyond the last index when each move can advance either 1 or 2 steps.
Example Input & Output
Step on 15 and then move past the end.
One low-cost path collects costs 1 + 1 + 1 + 1 + 1 + 1 = 6.
Land on the only step and finish.
Algorithm Flow
Solution Approach
Find the minimum cost to reach the top of a staircase where each step has a cost and you can climb 1 or 2 steps at a time. Use dynamic programming: dp[i] = cost[i] + min(dp[i-1], dp[i-2]). Start from step 0 or 1. The answer is min of the last two DP values.
Rolling variables replace the DP array for O(1) space. Each new cost combines with the minimum of the two preceding options.
Time complexity is O(n), space complexity is O(1).
Best Answers
class Solution {
public int min_cost_climbing_stairs(Object cost) {
int[] arr = (int[]) cost;
if (arr.length <= 1) {
return arr.length == 0 ? 0 : arr[0];
}
int prev2 = arr[0];
int prev1 = arr[1];
for (int i = 2; i < arr.length; i++) {
int curr = arr[i] + Math.min(prev1, prev2);
prev2 = prev1;
prev1 = curr;
}
return Math.min(prev1, prev2);
}
}Comments (0)
Join the Discussion
Share your thoughts, ask questions, or help others with this Challenge.
