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
2
3
4
5
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.

Constraints:

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

解答

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
/*
* @Description: 746. Min Cost Climbing Stairs
* @Author: libk
* @Github: https://github.com/libk
*/
/**
* @param {number[]} cost
* @return {number}
*/
const minCostClimbingStairs = function (cost) {
const n = cost.length
let pre = 0
let preOfPre = 0

for (let i = 2; i <= n; i++) {
let cur = Math.min(pre + cost[i - 1], preOfPre + cost[i - 2])
preOfPre = pre
pre = cur
}
return pre
}