Skip to content

746. Min Cost Climbing Stairs 👍

  • Time: $O(n)$
  • Space: $O(1)$
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
class Solution {
 public:
  int minCostClimbingStairs(vector<int>& cost) {
    const int n = cost.size();

    for (int i = 2; i < n; ++i)
      cost[i] += min(cost[i - 1], cost[i - 2]);

    return min(cost[n - 1], cost[n - 2]);
  }
};
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
class Solution {
  public int minCostClimbingStairs(int[] cost) {
    final int n = cost.length;

    for (int i = 2; i < n; ++i)
      cost[i] += Math.min(cost[i - 1], cost[i - 2]);

    return Math.min(cost[n - 1], cost[n - 2]);
  }
}
1
2
3
4
5
6
7
8
class Solution:
  def minCostClimbingStairs(self, cost: list[int]) -> int:
    cost.append(0)

    for i in range(2, len(cost)):
      cost[i] += min(cost[i - 1], cost[i - 2])

    return cost[-1]