Minimum Time to Break Locks I Problem
Description
LeetCode Problem 3376.
Bob is stuck in a dungeon and must break n locks, each requiring some amount of energy to break. The required energy for each lock is stored in an array called strength where strength[i] indicates the energy needed to break the i^th lock.
To break a lock, Bob uses a sword with the following characteristics:
- The initial energy of the sword is 0.
- The initial factor
xby which the energy of the sword increases is 1. - Every minute, the energy of the sword increases by the current factor
x. - To break the
i^thlock, the energy of the sword must reach at leaststrength[i]. - After breaking a lock, the energy of the sword resets to 0, and the factor
xincreases by a given valuek.
Your task is to determine the minimum time in minutes required for Bob to break all n locks and escape the dungeon.
Return the minimum time required for Bob to break all n locks.
Example 1:
Input: strength = [3,4,1], k = 1
Output: 4
Explanation:
Time Energy x Action Updated x
0 0 1 Nothing 1
1 1 1 Break 3^rd Lock 2
2 2 2 Nothing 2
3 4 2 Break 2^nd Lock 3
4 3 3 Break 1^st Lock 3
The locks cannot be broken in less than 4 minutes; thus, the answer is 4.
Example 2:
Input: strength = [2,5,4], k = 2
Output: 5
Explanation:
Time Energy x Action Updated x
0 0 1 Nothing 1
1 1 1 Nothing 1
2 2 1 Break 1^st Lock 3
3 3 3 Nothing 3
4 6 3 Break 2^nd Lock 5
5 5 5 Break 3^rd Lock 7
The locks cannot be broken in less than 5 minutes; thus, the answer is 5.
Constraints:
n == strength.length1 <= n <= 81 <= k <= 101 <= strength[i] <= 10^6
Solution
Approach: Bitmask DP
There are at most 8 locks, so we can try every order. The factor when breaking a lock depends only on how many locks are already broken: x = 1 + k * cnt. With factor x, a lock of strength s takes ceil(s / x) minutes.
Let dfs(mask) be the minimum time to finish the locks not in mask. When all locks are broken it is 0. Otherwise try each unbroken lock j, add ceil(strength[j] / x) and recurse into mask | (1 << j), taking the minimum. Memoize on mask. The answer is dfs(0).
Complexity: time O(2^n * n), space O(2^n), where n is the number of locks.
from math import inf
from functools import lru_cache
class Solution:
def findMinimumTime(self, strength: List[int], K: int) -> int:
@lru_cache(None)
def dfs(i: int) -> int:
if i == (1 << len(strength)) - 1:
return 0
cnt = bin(i).count("1")
x = 1 + cnt * K
ans = inf
for j, s in enumerate(strength):
if i >> j & 1 ^ 1:
ans = min(ans, dfs(i | 1 << j) + (s + x - 1) // x)
return ans
return dfs(0)