-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathMinCostClimbingStairs.java
More file actions
61 lines (56 loc) · 1.81 KB
/
MinCostClimbingStairs.java
File metadata and controls
61 lines (56 loc) · 1.81 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
package leetcode;
/**
* MinCostClimbingStairs
* https://leetcode-cn.com/problems/min-cost-climbing-stairs/
* 746. 使用最小花费爬楼梯
*
* @since 2020-12-21
*/
public class MinCostClimbingStairs {
public static void main(String[] args) {
MinCostClimbingStairs sol = new MinCostClimbingStairs();
System.out.println(sol.minCostClimbingStairs(new int[]{1, 100, 1, 1, 1, 100, 1, 1, 100, 1}));
System.out.println(sol.minCostClimbingStairs(new int[]{0, 0, 0, 1}));
System.out.println(sol.minCostClimbingStairs(new int[]{0, 1, 2, 2}));
}
public int minCostClimbingStairs(int[] cost) {
int[] steps = new int[cost.length];
for (int i = 0; i < cost.length; i++) {
int lastStep = 0;
if (i - 1 >= 0) {
lastStep = steps[i - 1];
}
if (i - 2 < 0) {
lastStep = 0;
} else if (steps[i - 2] < lastStep) {
lastStep = steps[i - 2];
}
steps[i] = lastStep + cost[i];
}
int total = 0;
if (cost.length - 1 >= 0) {
total = steps[cost.length - 1];
}
if (cost.length - 2 < 0) {
total = 0;
} else if (steps[cost.length - 2] < total) {
total = steps[cost.length - 2];
}
return total;
}
public int minCostClimbingStairs_fail(int[] cost) {
int total = 0;
int idx = -1;
while (idx + 1 < cost.length && idx + 2 < cost.length) {
if (idx + 2 < cost.length &&
total + cost[idx + 2] <= total + cost[idx + 1]) {
total += cost[idx + 2];
idx += 2;
} else {
total += cost[idx + 1];
idx += 1;
}
}
return total;
}
}