Min Cost Climbing Stairs LeetCode solution in JavaScript

1
var minCostClimbingStairs = function (cost) {
2
//this array will be populated with the minimum cost of each step starting from the top
3
let minCostArray = [];
4
//append a 0 at end to represent reaching the 'top'
5
minCostArray[cost.length] = 0;
6
//append the last stair to the end of the array
7
minCostArray[cost.length - 1] = cost[cost.length - 1];
8

9
//starts at -2 the length since we already have two elements in our array
10
for (let i = cost.length - 2; i > -1; i--) {
11
//checks which minimum cost is lower and assigns the value at that index accordingly
12
if (minCostArray[i + 1] < minCostArray[i + 2])
13
minCostArray[i] = cost[i] + minCostArray[i + 1];
14
else minCostArray[i] = cost[i] + minCostArray[i + 2];
15
}
16
//checks which of the first two options is the lowest cost
17
return minCostArray[0] > minCostArray[1] ? minCostArray[1] : minCostArray[0];
18
};

0

WPM •0 •0

100%

ACC •0 •0

0s

TIME •0