#330
Hard Algorithms Patching array
Array Greedy
54.1% acceptance
Jan 12, 2026
2427
202
Given a sorted integer array nums and an integer n, add/patch elements to the array such that any number in the range [1, n] inclusive can be formed by the sum of some elements in the array.
Return the minimum number of patches required.
Solution
Rust
Time O(n)
Space O(1)
impl Solution {
pub fn min_patches(nums: Vec<i32>, n: i32) -> i32 {
let mut miss: i64 = 1;
let mut patches = 0;
let mut i = 0;
let n = n as i64;
while miss <= n {
if i < nums.len() && nums[i] as i64 <= miss {
miss += nums[i] as i64;
i += 1;
} else {
miss += miss;
patches += 1;
}
}
patches
}
}