Minimum Cost to Set Cooking Time LeetCode solution in JavaScript

1
/**
2
* @param {number} startAt
3
* @param {number} moveCost
4
* @param {number} pushCost
5
* @param {number} targetSeconds
6
* @return {number}
7
*/
8
var minCostSetTime = function (startAt, moveCost, pushCost, targetSeconds) {
9
let cost = Infinity;
10

11
let maxMinutes = Math.floor(targetSeconds / 60);
12

13
for (let min = 0; min <= maxMinutes; min++) {
14
let secs = targetSeconds - min * 60;
15

16
if (secs > 99 || min > 99) continue;
17

18
let buttons = String(100 * min + secs);
19
let prev = Number(buttons[0]);
20

21
let sum = 0;
22

23
//start index will vary according to startAt pointer
24
let start = 0;
25

26
//If startAt is equal to first button, we need to add pushCost fatigue
27
if (prev === startAt) {
28
sum += pushCost;
29
start = 1;
30
} else {
31
//Else we need to add moveCost fatigue
32
sum += moveCost;
33
}
34

35
for (let i = start; i < buttons.length; i++) {
36
let button = Number(buttons[i]);
37

38
if (button !== prev) {
39
sum += moveCost + pushCost;
40
} else {
41
sum += pushCost;
42
}
43

44
prev = button;
45
}
46

47
cost = Math.min(cost, sum);
48
}
49

50
return cost;
51
};

0

WPM •0 •0

100%

ACC •0 •0

0s

TIME •0