[leetcode] 746. Min Cost Climbing Stairs

반응형

문제

You are given an integer array cost where cost[i] is the cost of ith step on a staircase. Once you pay the cost, you can either climb one or two steps.

You can either start from the step with index 0, or the step with index 1.

Return the minimum cost to reach the top of the floor.

 

 

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].

 

Constraints:

  • 2 <= cost.length <= 1000
  • 0 <= cost[i] <= 999

풀이

한번에 한칸이나 두칸의 계단을 올 수 있다. 각 계단마다는 비용이 존재하고 가장 마지막까지 가는 최소 비용을 구하는 문제이다.

Dynamic Programming 풀면 되는 문제이다.

 

<파이썬 알고리즘 인터뷰> &nbsp;p.624, 책만, 2020

 


코드

내가 푼 풀이

    public int minCostClimbingStairs(int[] cost) {
        int[] dp = new int[cost.length + 1];

        for (int i = 2; i < dp.length; i++) {
            int oneStep = dp[i - 1] + cost[i - 1];
            int twoStep = dp[i - 2] + cost[i - 2];

            dp[i] = Math.min(oneStep, twoStep);
        }

        return dp[dp.length - 1];
    }

이렇게 풀면 복잡도는 다음과 같다.

Time: O(N)

 

 

discuss를 보니 아래와 같이 공간 복잡도를 최적화할 수 있는 풀이가 존재한다.

public int minCostClimbingStairs(int[] cost) {
  int n = cost.length;
  int f1 = 0, f2 = 0; // init
  for (int i = 2; i <= n; ++i) {
    int temp = Math.min(f1 + cost[i - 2], f2 + cost[i - 1]); // [i - 2] is before
    f1 = f2;
    f2 = temp;
  }
  return f2;
}

Time: O(N)
Space: O(1)

 

 

 

 


참고