LeetCode 75
Min Cost Climbing Stairs
- Problem
- LC 746
- Topic
- DP 1D
- File
- official75_LC746MinCostClimbingStairs.java
- Path
- pkg5leetcode/official75/official75_LC746MinCostClimbingStairs.java
- Package
- pkg5leetcode.official75
- Command
- java pkg5leetcode/official75/official75_LC746MinCostClimbingStairs.java
- Approach
- DP min cost to reach each step.
- Complexity
- Time O(n), Space O(1)
There is no in-browser runner. This is the file from the curriculum, unchanged.
1package pkg5leetcode.official75;2 3/*4 * Min Cost Climbing Stairs | LC 7465 * APPROACH: DP min cost to reach each step.6 * COMPLEXITY: Time O(n), Space O(1)7 */8public class official75_LC746MinCostClimbingStairs {9 static int minCostClimbingStairs(int[] cost) {10 int a = 0, b = 0;11 for (int i = 2; i <= cost.length; i++) {12 int c = Math.min(b + cost[i - 1], a + cost[i - 2]);13 a = b; b = c;14 }15 return b;16 }17 18 public static void main(String[] args) {19 check(minCostClimbingStairs(new int[]{10,15,20}) == 15, "case1");20 check(minCostClimbingStairs(new int[]{1,100,1,1,1,100,1,1,100,1}) == 6, "case2");21 System.out.println("all tests passed");22 }23 24 static void check(boolean cond, String name) {25 if (!cond) throw new AssertionError("FAILED: " + name);26 System.out.println(" PASS " + name);27 }28}