746. Min Cost Climbing Stairs

Question

On a staircase, the i-th step has some non-negative cost cost[i] assigned (0 indexed).

Once you pay the cost, you can either climb one or two steps. You need to find minimum cost to reach the top of the floor, and you can either start from the step with index 0, or the step with index 1.

Example 1:

Input: cost = [10, 15, 20]
Output: 15
Explanation: Cheapest is start on cost[1], pay that cost and go to the top.

Example 2:

Input: cost = [1, 100, 1, 1, 1, 100, 1, 1, 100, 1]
Output: 6
Explanation: Cheapest is start on cost[0], and only step on 1s, skipping cost[3].

Note:

  1. cost will have a length in the range [2, 1000].
  2. Every cost[i] will be an integer in the range [0, 999].

Solution

  • Method 1:dp
    • dp[n + 1]: n + 1 means the top of the stairs whose cost is 0.
    • Initialization: dp[0] = cost[0], dp[1] = cost[1]: we can either start from 0 or 1.
    • transfer function: dp[i] = min(dp[i - 1], dp[i - 2]) + cost[i]
        class Solution {
        public int minCostClimbingStairs(int[] cost) {
            int n = cost.length;
            int[] dp = new int[n + 1];
            dp[0] = cost[0];
            dp[1] = cost[1];
            for(int i = 2; i <= n; i++){
                int cur = i == n ? 0: cost[i];
                dp[i] = cur + Math.min(dp[i - 1], dp[i - 2]);
            }
            return dp[n];
        }
        }
      

Amazon session

class Solution {
    public int minCostClimbingStairs(int[] cost) {
        int[] dp = new int[cost.length + 2];   // save the minimum cost reaching current stage.
        // we initialize dp[0] = 0;
        for(int i = 1; i <= cost.length + 1; i++){
            // cur[i - 1], dp[i]
            // 2 conditions:
            //1. 1 step to current stage: dp[i] = cost[i] + dp[i - 1]
            //2. 2 steps to current stage: dp[i] = cost[i - 1] + dp[i - 2];
            dp[i] = Math.min(((i - 2 >= 0 ? cost[i - 2]: 0) + dp[i - 1]),
                            (i - 3 >= 0 ? cost[i - 3]: 0) + (i - 2 >= 0 ? dp[i - 2]: 0));
        }
        return dp[cost.length + 1];
    }
}