Skip to content

2162. Minimum Cost to Set Cooking Time 👎

  • Time: $O(1)$
  • Space: $O(1)$
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
class Solution {
 public:
  int minCostSetTime(int startAt, int moveCost, int pushCost,
                     int targetSeconds) {
    int ans = INT_MAX;
    int mins = targetSeconds > 5999 ? 99 : targetSeconds / 60;
    int secs = targetSeconds - mins * 60;

    auto getCost = [&](int mins, int secs) -> int {
      int cost = 0;
      char curr = '0' + startAt;
      for (const char c : to_string(mins * 100 + secs))
        if (c == curr) {
          cost += pushCost;
        } else {
          cost += moveCost + pushCost;
          curr = c;
        }
      return cost;
    };

    while (secs < 100) {
      ans = min(ans, getCost(mins, secs));
      --mins;
      secs += 60;
    }

    return ans;
  }
};
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
class Solution {
  public int minCostSetTime(int startAt, int moveCost, int pushCost, int targetSeconds) {
    int ans = Integer.MAX_VALUE;
    int mins = targetSeconds > 5999 ? 99 : targetSeconds / 60;
    int secs = targetSeconds - mins * 60;

    while (secs < 100) {
      ans = Math.min(ans, getCost(startAt, moveCost, pushCost, mins, secs));
      --mins;
      secs += 60;
    }

    return ans;
  }

  private int getCost(int startAt, int moveCost, int pushCost, int mins, int secs) {
    int cost = 0;
    char curr = (char) ('0' + startAt);
    for (final char c : String.valueOf(mins * 100 + secs).toCharArray())
      if (c == curr) {
        cost += pushCost;
      } else {
        cost += moveCost + pushCost;
        curr = c;
      }
    return cost;
  };
}
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
class Solution:
  def minCostSetTime(
      self,
      startAt: int,
      moveCost: int,
      pushCost: int,
      targetSeconds: int,
  ) -> int:
    ans = math.inf
    mins = 99 if targetSeconds > 5999 else targetSeconds // 60
    secs = targetSeconds - mins * 60

    def getCost(mins: int, secs: int) -> int:
      cost = 0
      curr = str(startAt)
      for c in str(mins * 100 + secs):
        if c == curr:
          cost += pushCost
        else:
          cost += moveCost + pushCost
          curr = c
      return cost

    while secs < 100:
      ans = min(ans, getCost(mins, secs))
      mins -= 1
      secs += 60

    return ans