|
| 1 | +/* |
| 2 | + * @lc app=leetcode id=746 lang=cpp |
| 3 | + * |
| 4 | + * [746] Min Cost Climbing Stairs |
| 5 | + * |
| 6 | + * https://leetcode.com/problems/min-cost-climbing-stairs/description/ |
| 7 | + * |
| 8 | + * algorithms |
| 9 | + * Easy (46.04%) |
| 10 | + * Total Accepted: 68.1K |
| 11 | + * Total Submissions: 147.6K |
| 12 | + * Testcase Example: '[0,0,0,0]' |
| 13 | + * |
| 14 | + * |
| 15 | + * On a staircase, the i-th step has some non-negative cost cost[i] assigned (0 |
| 16 | + * indexed). |
| 17 | + * |
| 18 | + * Once you pay the cost, you can either climb one or two steps. You need to |
| 19 | + * find minimum cost to reach the top of the floor, and you can either start |
| 20 | + * from the step with index 0, or the step with index 1. |
| 21 | + * |
| 22 | + * |
| 23 | + * Example 1: |
| 24 | + * |
| 25 | + * Input: cost = [10, 15, 20] |
| 26 | + * Output: 15 |
| 27 | + * Explanation: Cheapest is start on cost[1], pay that cost and go to the |
| 28 | + * top. |
| 29 | + * |
| 30 | + * |
| 31 | + * |
| 32 | + * Example 2: |
| 33 | + * |
| 34 | + * Input: cost = [1, 100, 1, 1, 1, 100, 1, 1, 100, 1] |
| 35 | + * Output: 6 |
| 36 | + * Explanation: Cheapest is start on cost[0], and only step on 1s, skipping |
| 37 | + * cost[3]. |
| 38 | + * |
| 39 | + * |
| 40 | + * |
| 41 | + * Note: |
| 42 | + * |
| 43 | + * cost will have a length in the range [2, 1000]. |
| 44 | + * Every cost[i] will be an integer in the range [0, 999]. |
| 45 | + * |
| 46 | + * |
| 47 | + */ |
| 48 | +class Solution |
| 49 | +{ |
| 50 | + public: |
| 51 | + int minCostClimbingStairs(vector<int> &cost) |
| 52 | + { |
| 53 | + int s = cost.size(); |
| 54 | + if (s == 0) |
| 55 | + return 0; |
| 56 | + if (s == 1) |
| 57 | + return cost[0]; |
| 58 | + int a[] = {cost[0], cost[1]}; |
| 59 | + for (int i = 2; i < s; i++) |
| 60 | + { |
| 61 | + a[i % 2] = min(cost[i] + a[0], cost[i] + a[1]); |
| 62 | + } |
| 63 | + return min(a[0], a[1]); |
| 64 | + } |
| 65 | +}; |
0 commit comments