#3385
Hard Algorithms Minimum time to break locks ii
Array Breadth-First Search Graph Theory
45.1% acceptance
Mar 31, 2026
5
1
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 1.
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>) -> i32 {
let n = strength.len();
// Hungarian algorithm for min-cost bipartite matching
// Worker i = lock i, Job j = position j (X = j, 1-indexed)
// cost(i, j) = ceil(strength[i] / j)
let inf = i64::MAX / 2;
let mut u = vec![0i64; n + 1];
let mut v = vec![0i64; n + 1];
let mut p = vec![0usize; n + 1];
let mut way = vec![0usize; n + 1];
for i in 1..=n {
p[0] = i;
let mut j0 = 0usize;
let mut minv = vec![inf; n + 1];
let mut used = vec![false; n + 1];
loop {
used[j0] = true;
let i0 = p[j0];
let mut delta = inf;
let mut j1 = 0usize;
for j in 1..=n {
if !used[j] {
let cost = ((strength[i0 - 1] as i64) + (j as i64) - 1) / (j as i64);
let cur = cost - u[i0] - v[j];
if cur < minv[j] {
minv[j] = cur;
way[j] = j0;
}
if minv[j] < delta {
delta = minv[j];
j1 = j;
}
}
}
for j in 0..=n {
if used[j] {
u[p[j]] += delta;
v[j] -= delta;
} else {
minv[j] -= delta;
}
}
j0 = j1;
if p[j0] == 0 {
break;
}
}
loop {
let j1 = way[j0];
p[j0] = p[j1];
j0 = j1;
if j0 == 0 {
break;
}
}
}
let mut result = 0i64;
for j in 1..=n {
if p[j] != 0 {
result += ((strength[p[j] - 1] as i64) + (j as i64) - 1) / (j as i64);
}
}
result as i32
}
}