Problem Description
Given two arrays, nums and target, you can increment any element in nums by one per operation. The goal is to achieve the minimum total number of operations such that for every element t in target, there is at least one number in nums (after performing increments) that is a multiple of t.
Key Insights
- Each number in nums can be incremented until it becomes a multiple of a given target value.
- A single modified number might cover more than one target if it is a multiple of the least common multiple (LCM) of a subset of targets.
- Since target’s size is at most 4, we can iterate over all non-empty subsets (up to 15) of target indices.
- For each nums element and each non-empty subset of target, calculate the cost to increase the number to the smallest multiple of the LCM of that subset that is no less than the element.
- Use dynamic programming (DP) with bitmask states (where each bit represents whether a target is covered) to combine the contributions of different nums elements optimally.
Space and Time Complexity
Time Complexity: O(N * 2^T * 2^T) where T <= 4, so effectively O(N) ≈ O(5×10^4) Space Complexity: O(2^T) = O(16)
Solution
The solution reduces to a minimum cost cover problem over a set of targets. For each number in nums, we:
- Compute the cost to convert it into a multiple of the LCM of every non-empty subset of targets.
- Use a DP array (indexed by a bitmask of length T) to track the minimum cost required to cover each subset of targets.
- For each number, update the DP states: for every current state (mask) and every possible subset that the current number can cover (with cost computed), update the state corresponding to the union of these targets.
- The final answer is found in the DP state corresponding to the full mask, i.e. all targets covered.
The “trick” is to realize that one incremented nums element may serve double duty by covering multiple target numbers simultaneously if it becomes a multiple of their LCM.