#3376
Medium Algorithms Minimum time to break locks i
Array Dynamic Programming Backtracking Bit Manipulation Depth-First Search Bitmask
32.1% acceptance
Feb 24, 2026
104
25
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 ith lock.
To break a lock, Bob uses a sword with the following characteristics:
The initial energy of the sword is 0.
The initial factor x by 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 ith lock, the energy of the sword must reach at least strength[i].
After breaking a lock, the energy of the sword resets to 0, and the factor x increases by a given value k.
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.
Solution
Rust
Time O(n²)
Space O(n)
impl Solution {
pub fn find_minimum_time(strength: Vec<i32>, k: i32) -> i32 {
let n = strength.len();
// Bitmask DP: dp[mask] = min time to break all locks in mask
// When breaking locks in a given permutation, the xth lock broken uses factor = 1 + (x-1)*k
// Time to break one lock with factor f = ceil(s / f)
let mut dp = vec![i32::MAX; 1 << n];
dp[0] = 0;
for mask in 0..(1u32 << n) {
if dp[mask as usize] == i32::MAX {
continue;
}
let count = mask.count_ones() as i32; // locks already broken
let factor = 1 + count * k;
for i in 0..n {
if mask & (1 << i) == 0 {
let time_needed = (strength[i] + factor - 1) / factor;
let new_mask = mask | (1 << i);
let new_time = dp[mask as usize] + time_needed;
if new_time < dp[new_mask as usize] {
dp[new_mask as usize] = new_time;
}
}
}
}
dp[(1 << n) - 1]
}
}