Minimum Increments for Target Multiples in an Array - Problem

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.

A multiple of a number x is any number that can be expressed as k * x where k is a positive integer.

Input & Output

Example 1 — Basic Case
$ Input: nums = [1,2,3], target = [2,4]
Output: 1
💡 Note: Optimal assignment: nums[1]=2 to target[0]=2 (cost 0, since 2 is already a multiple of 2), nums[2]=3 to target[1]=4 (cost 1, since we need 4 which is 3+1). Total cost: 0+1=1.
Example 2 — Zero Elements
$ Input: nums = [0,0,0], target = [1,2,3]
Output: 6
💡 Note: Transform 0→1 (cost 1), 0→2 (cost 2), 0→3 (cost 3). Total cost: 1+2+3=6.
Example 3 — Multiple Assignment
$ Input: nums = [3,5], target = [2,4]
Output: 2
💡 Note: Optimal assignment: nums[0]=3 to target[1]=4 (cost 1, since we need 4 which is 3+1), nums[1]=5 to target[0]=2 (cost 1, since we need 6 which is the smallest multiple of 2 that's ≥5, costing 6-5=1). Total cost: 1+1=2.

Constraints

  • 1 ≤ nums.length, target.length ≤ 8
  • 1 ≤ nums[i], target[i] ≤ 100

Visualization

Tap to expand
Minimum Increments for Target Multiples INPUT nums array 1 2 3 [0] [1] [2] target array 2 4 [0] [1] Goal: Make sure nums contains at least one multiple of each target element ALGORITHM STEPS 1 Find multiples needed Target 2: multiples 2,4,6... Target 4: multiples 4,8,12... 2 Check existing nums nums[1]=2 is multiple of 2 [OK] No multiple of 4 exists yet 3 Find min increments 1 --> 4: needs 3 increments 2 --> 4: needs 2 increments 3 --> 4: needs 1 increment 4 Optimal assignment Use bitmask DP to cover all targets with min cost Best Strategy: Increment 3 --> 4 (1 op) 4 covers both targets! Wait: need separate coverage FINAL RESULT Original nums: 1 2 3 After increments: 4 2 3 +3 +0 Coverage Check: Target 2: covered by 2 [OK] Target 4: covered by 4 [OK] OUTPUT 3 Key Insight: Use bitmask DP where each state represents which targets are covered. For each number in nums, calculate the minimum increments to reach the next multiple of each target. A single increment can potentially satisfy multiple targets if the resulting number is a common multiple (e.g., 4 is multiple of both 2 and 4). TutorialsPoint - Minimum Increments for Target Multiples in an Array | Optimal Solution
Asked in
Google 15 Microsoft 12 Amazon 8
8.5K Views
Medium Frequency
~35 min Avg. Time
245 Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen