#3444
Hard Algorithms Minimum increments for target multiples in an array
Array Math Dynamic Programming Bit Manipulation Number Theory Bitmask
27.4% acceptance
Feb 25, 2026
87
7
You are given two arrays, nums and target.
In a single operation, you may increment any element of nums by 1.
Return the minimum number of operations required so that each element in target has at least one multiple in nums.
Solution
Rust
Time O(n³)
Space O(n)
impl Solution {
pub fn minimum_increments(nums: Vec<i32>, target: Vec<i32>) -> i64 {
let t = target.len();
let full = (1usize << t) - 1;
fn gcd(a: i64, b: i64) -> i64 { if b == 0 { a } else { gcd(b, a % b) } }
fn lcm(a: i64, b: i64) -> i64 { a / gcd(a, b) * b }
// Precompute lcm for each non-empty subset of target
let mut subset_lcm = vec![1i64; 1 << t];
for mask in 1..=(1 << t) - 1usize {
let mut l = 1i64;
for i in 0..t {
if mask & (1 << i) != 0 { l = lcm(l, target[i] as i64); }
}
subset_lcm[mask] = l;
}
// Per-element DP: dp[mask] = min cost so that all targets in mask are covered.
// Process each nums element once, deciding which subset of targets it covers.
// Cloning state before each element prevents reusing the same element for two groups.
let inf = i64::MAX / 2;
let mut dp = vec![inf; 1 << t];
dp[0] = 0;
for &x in &nums {
let x = x as i64;
let prev = dp.clone();
for sub in 1..=(1 << t) - 1usize {
let l = subset_lcm[sub];
let cost = (l - x % l) % l;
for mask in 0..=(1 << t) - 1usize {
if prev[mask] < inf {
let new_mask = mask | sub;
let candidate = prev[mask] + cost;
if candidate < dp[new_mask] {
dp[new_mask] = candidate;
}
}
}
}
}
dp[full]
}
}