99클럽 코테 스터디 40일차 TIL | Min Cost Climbing Stairs

fever·2024년 8월 30일
0

99클럽 코테 스터디

목록 보기
40/42
post-thumbnail

🖥️ 문제

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: You will start at index 1.

  • Pay 15 and climb two steps to reach the top.
    The total cost is 15.

Example 2:
Input: cost = [1,100,1,1,1,100,1,1,100,1]
Output: 6

Explanation: You will start at index 0.

  • Pay 1 and climb two steps to reach index 2.
  • Pay 1 and climb two steps to reach index 4.
  • Pay 1 and climb two steps to reach index 6.
  • Pay 1 and climb one step to reach index 7.
  • Pay 1 and climb two steps to reach index 9.
  • Pay 1 and climb one step to reach the top.
    The total cost is 6.

📝 풀이

class Solution {
    public int minCostClimbingStairs(int[] cost) {
        int n = cost.length;
        
        // 초기화: 마지막 두 계단의 비용
        int prev1 = cost[n - 1];
        int prev2 = cost[n - 2];
        
        // 역순으로 계산하여 최소 비용을 추적
        for (int i = n - 3; i >= 0; i--) {
            int curr = cost[i] + Math.min(prev1, prev2);
            prev1 = prev2;
            prev2 = curr;
        }
        
        // 시작점에서의 최소 비용 반환
        return Math.min(prev1, prev2);
    }
}

문제는 계단을 올라가는 데 드는 최소 비용을 구하는 것이다.
계단 i에 도달하는 최소 비용은 cost[i]i-1i-2 계단까지의 최소 비용 중 더 작은 값의 합이다.

이후 배열의 마지막 두 계단부터 역순으로 시작하여 각 계단에 도달하는 최소 비용을 계산했다. 끝으로는 시작점에서의 최소 비용 중 더 작은 값을 반환한다.

profile
선명한 삶을 살기 위하여

0개의 댓글