#2162
Minimum Cost to Set Cooking Time
MediumMathEnumerationEnumerationDynamic Programming
Approaches
Brute ForceOptimal
Complexity Comparison
| Brute Force | Optimal Solution★ | |
|---|---|---|
| Time | O(n²) | O(n) |
| Space | O(1) | O(1) |
💡
Intuition
Time O(n)Space O(1)
Instead of brute-forcing through all combinations, we can directly calculate the cost for each valid minute and second combination that sums to targetSeconds. This reduces unnecessary calculations and speeds up the process.
⚙️
Algorithm
5 steps- 1Step 1: Calculate target minutes and seconds from targetSeconds.
- 2Step 2: Loop through all valid minutes from 0 to 99.
- 3Step 3: For each minute, calculate the corresponding seconds needed to reach targetSeconds.
- 4Step 4: Use the Cost function to compute the cost for valid combinations.
- 5Step 5: Track the minimum cost.
solution.py18 lines
1def minCost(startAt, moveCost, pushCost, targetSeconds):
2 minCost = float('inf')
3 for mm in range(100):
4 ss = targetSeconds - mm * 60
5 if 0 <= ss < 60:
6 cost = Cost(mm, ss, startAt, moveCost, pushCost)
7 minCost = min(minCost, cost)
8 return minCost
9
10def Cost(mm, ss, startAt, moveCost, pushCost):
11 digits = f'{mm:02}{ss:02}'
12 cost = 0
13 for digit in digits:
14 if int(digit) != startAt:
15 cost += moveCost
16 cost += pushCost
17 startAt = int(digit)
18 return costℹ
Complexity note: The time complexity is O(n) because we iterate through a maximum of 100 minutes, and for each valid minute, we perform a constant amount of work. The space complexity is O(1) since we only use a fixed amount of space.
- 1The range of minutes is small (0-99), allowing for enumeration.
- 2Cost calculation is dependent on the sequence of digits pushed.
Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.