Minimum Increments for Target Multiples in an Array Problem
Description
LeetCode Problem 3444.
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.
Example 1:
Input: nums = [1,2,3], target = [4]
Output: 1
Explanation:
The minimum number of operations required to satisfy the condition is 1.
- Increment 3 to 4 with just one operation, making 4 a multiple of itself.
Example 2:
Input: nums = [8,4], target = [10,5]
Output: 2
Explanation:
The minimum number of operations required to satisfy the condition is 2.
- Increment 8 to 10 with 2 operations, making 10 a multiple of both 5 and 10.
Example 3:
Input: nums = [7,9,10], target = [7]
Output: 0
Explanation:
Target 7 already has a multiple in nums, so no additional operations are needed.
Constraints:
1 <= nums.length <= 5 * 10^41 <= target.length <= 4target.length <= nums.length1 <= nums[i], target[i] <= 10^4
Solution
Approach: Bitmask DP
There are at most 4 targets. Let lcm[t] be the least common multiple of the targets in subset t. One element x can cover all the targets of t by being raised to the next multiple of lcm[t], which costs (lcm[t] - x % lcm[t]) % lcm[t]. (Cap the lcm at a large value such as 10^9: any cost that big is never useful, because covering every target separately costs at most 4 * 10^4.)
Let f[mask] be the minimum total cost to cover the targets in mask. For each element, build a new array g from the old one: for every subset t and every mask, g[mask | t] = min(g[mask | t], f[mask] + cost(x, t)). Using a fresh array ensures each element is used at most once. The answer is f[full].
(The Python version first keeps only the 4 cheapest elements for each subset, since an optimal answer uses at most 4 elements.)
Complexity: O(n * 4^m) time and O(2^m) space, where m <= 4 is the number of targets.
class Solution:
def minimumIncrements(self, nums: List[int], target: List[int]) -> int:
from math import gcd
from heapq import nsmallest
m = len(target)
full = (1 << m) - 1
# lcm of the targets in each subset
lcm = [1] * (full + 1)
for t in range(1, full + 1):
low = t & -t
v = target[low.bit_length() - 1]
u = lcm[t ^ low]
lcm[t] = u // gcd(u, v) * v
# at most 4 elements are used, so only the 4 cheapest per subset matter
cand = set()
for t in range(1, full + 1):
L = lcm[t]
cand.update(nsmallest(4, range(len(nums)), key=lambda j: -nums[j] % L))
INF = float("inf")
f = [INF] * (full + 1)
f[0] = 0
for j in cand:
x = nums[j]
g = f[:]
for t in range(1, full + 1):
c = -x % lcm[t]
for mask in range(full + 1):
if f[mask] + c < g[mask | t]:
g[mask | t] = f[mask] + c
f = g
return f[full]