#2162
Medium Algorithms Minimum cost to set cooking time
Math Enumeration
41.5% acceptance
Feb 25, 2026
236
644
A generic microwave supports cooking times from at least 1 second to at most 99 minutes
and 99 seconds. To set cooking time, push at most four digits (padded to 4 with leading zeros).
First two digits = minutes, last two = seconds.
You have startAt finger position, moveCost per move, pushCost per push.
Return the minimum cost to set targetSeconds seconds of cooking time.
Solution
Rust
Time O(n²)
Space O(n)
impl Solution {
pub fn min_cost_set_time(
start_at: i32,
move_cost: i32,
push_cost: i32,
target_seconds: i32,
) -> i32 {
let mut best = i32::MAX;
for m in 0..=99i32 {
let s = target_seconds - m * 60;
if s < 0 || s > 99 {
continue;
}
// Encode as number (strip leading zeros)
let combined = m * 100 + s;
let digits: Vec<i32> = if combined == 0 {
vec![0]
} else {
let mut d = Vec::new();
let mut x = combined;
while x > 0 {
d.push(x % 10);
x /= 10;
}
d.reverse();
d
};
let mut cost = 0i32;
let mut prev = start_at;
for &d in &digits {
if d != prev {
cost += move_cost;
}
cost += push_cost;
prev = d;
}
best = best.min(cost);
}
best
}
}