min-cost-climbing-stairs.dart (1199B)
1 //Find the minimum amount of energy required to make it up stairs. 2 //Each stair has a difficulty and each step can move up by one or two stairs. 3 //The time complexity of this code is O(n) where n is the number of values in the 4 //list. 5 //Time: 324ms Beats: 36.36% 6 //Memory: 175.9MB Beats: 9.9% 7 8 class Solution { 9 Map<int, int> memo = {}; 10 int minCostClimbingStairs(List<int> cost) { 11 int first = recurse(cost.sublist(1)); 12 int second = recurse(cost); 13 if (first > second) { 14 return second; 15 } 16 return first; 17 } 18 19 int recurse(List<int> cost) { 20 if(memo[cost.length] != null){ 21 return(memo[cost.length] ?? 0); 22 } 23 if (cost.length == 0) { 24 return 0; 25 } 26 if (cost.length == 1) { 27 return cost[0]; 28 } 29 int first = recurse(cost.sublist(1)); 30 int second = recurse(cost.sublist(2)); 31 if (first < second) { 32 int return_val = first + cost[0]; 33 memo[cost.length] = return_val; 34 return return_val; 35 } 36 int return_val = second + cost[0]; 37 memo[cost.length] = return_val; 38 return return_val; 39 } 40 }