Code Logo

Minimum Cost to Reach the Top

Published at05 Jan 2026
Array Manipulation Easy 11 views
Like16

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

Example 1
Input
costs = [10, 15, 20]
Output
15
Explanation

Step on 15 and then move past the end.

Example 2
Input
costs = [1, 100, 1, 1, 1, 100, 1, 1, 100, 1]
Output
6
Explanation

One low-cost path collects costs 1 + 1 + 1 + 1 + 1 + 1 = 6.

Example 3
Input
costs = [5]
Output
5
Explanation

Land on the only step and finish.

Algorithm Flow

Recommendation Algorithm Flow for Minimum Cost to Reach the Top

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.

function minCostClimbingStairs(cost) {
  var a = cost[0], b = cost[1];
  for (var i = 2; i < cost.length; i++) {
    var c = cost[i] + Math.min(a, b);
    a = b; b = c;
  }
  return Math.min(a, b);
}

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

java
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);
    }
}