Minimum Operations to Form Subset Sum II Problem
Description
LeetCode Problem 4041.
You are given an integer array nums and an integer sum.
In one operation, choose an element with current value x and replace it with either 2 * x or floor(x / 2).
For each element, multiplication and division operations may be performed in any order.
Return the minimum number of operations needed so that some subset of the resulting array has a sum exactly equal to sum. If it is impossible, return -1.
The floor() function returns the integer part of the division.
Example 1:
Input: nums = [10,2], sum = 13
Output: 3
Explanation:
- Divide nums[0] = 10 once: 10 → 5, costing 1 operation.
- Multiply nums[1] = 2 twice: 2 → 4 → 8, costing 2 operations.
- After these operations, nums = [5, 8]. The subset {5, 8} sums to 13 using 3 operations in total.
Example 2:
Input: nums = [6,3], sum = 8
Output: 2
Explanation:
- Turn nums[1] = 3 into 2 using 2 operations:
- Divide nums[1] to get 1.
- Multiply nums[1] = 1 to get 2.
- After these operations, nums = [6, 2]. The subset {6, 2} sums to 8 using 2 operations in total.
Example 3:
Input: nums = [2,2], sum = 7
Output: -1
Explanation:
- No sequence of operations lets a subset of nums sum to 7, so the answer is -1.
Constraints:
1 <= nums.length <= 1001 <= nums[i] <= 5001 <= sum <= 5000
Solution
Approach: 0-1 Knapsack
Now multiplications and divisions can come in any order. A multiplication directly followed by a division cancels out, because floor(2x / 2) = x, so such a pair only wastes two operations. After cancelling all such pairs, every sequence becomes "divide i times, then multiply j times", which turns x into floor(x / 2^i) * 2^j at a cost of i + j.
Each element contributes at most one (value, cost) pair to the subset, so this is a 0-1 knapsack with exact capacity sum.
Let f[w] be the minimum number of operations for a subset to sum to exactly w, with f[0] = 0 and everything else infinite. For each element x, go through w from large to small, enumerate i divisions and j multiplications to get y = floor(x / 2^i) * 2^j, and update f[w] = min(f[w], f[w - y] + i + j) when y <= w. If f[sum] is still infinite, return -1.
Complexity: O(n * S * log M * log S) time and O(S) space, where n is the length of nums, M its maximum value and S is sum.
class Solution:
def minOperations(self, nums: List[int], sum: int) -> int:
inf = 10**9
f = [0] + [inf] * sum
for x in nums:
for w in range(sum, -1, -1):
i, y = 0, x
while y <= w:
f[w] = min(f[w], f[w - y] + i)
i += 1
y *= 2
i, y = 1, x // 2
while y > 0:
j, z = 0, y
while z <= w:
f[w] = min(f[w], f[w - z] + i + j)
j += 1
z *= 2
i += 1
y //= 2
return -1 if f[sum] == inf else f[sum]