[LeetCode] Minimum Cost to Set Cooking Time

2162. Minimum Cost to Set Cooking Time

A generic microwave supports cooking times for:

  • at least 1 second.
  • at most 99 minutes and 99 seconds.

To set the cooking time, you push at most four digits. The microwave normalizes what you push as four digits by prepending zeroes. It interprets the first two digits as the minutes and the last two digits as the seconds. It then adds them up as the cooking time. For example,

  • You push 9 5 4 (three digits). It is normalized as 0954 and interpreted as 9 minutes and 54 seconds.
  • You push 0 0 0 8 (four digits). It is interpreted as 0 minutes and 8 seconds.
  • You push 8 0 9 0. It is interpreted as 80 minutes and 90 seconds.
  • You push 8 1 3 0. It is interpreted as 81 minutes and 30 seconds.

You are given integers startAt, moveCost, pushCost, and targetSeconds. Initially, your finger is on the digit startAt. Moving the finger above any specific digit costs moveCost units of fatigue. Pushing the digit below the finger once costs pushCost units of fatigue.

There can be multiple ways to set the microwave to cook for targetSeconds seconds but you are interested in the way with the minimum cost.

Return the minimum cost to set targetSeconds seconds of cooking time.

Remember that one minute consists of 60 seconds.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
class Solution {
int solution(int st, int& mv, int& push, int mi, int sec) {
if(mi >= 100) return INT_MAX;
string seq = to_string(mi * 100 + sec);
int res = 0;
for(auto& ch : seq) {
if((ch & 0b1111) != st) res += mv;
res += push;
st = (ch & 0b1111);
}
return res;
}
public:
int minCostSetTime(int startAt, int moveCost, int pushCost, int targetSeconds) {
int mi = targetSeconds / 60;
int sec = targetSeconds % 60;
return min(solution(startAt, moveCost, pushCost, mi, sec),
mi and sec <= 39 ? solution(startAt, moveCost, pushCost, mi - 1, sec + 60) : INT_MAX);
}
};
Author: Song Hayoung
Link: https://songhayoung.github.io/2022/02/08/PS/LeetCode/minimum-cost-to-set-cooking-time/
Copyright Notice: All articles in this blog are licensed under CC BY-NC-SA 4.0 unless stating additionally.