Minimum Operations to Form Subsequence With Target Sum - Problem

Minimum Operations to Form Subsequence With Target Sum

You're given an array nums containing only powers of 2 (like 1, 2, 4, 8, 16...) and need to find the minimum number of operations to create a subsequence that sums to a target value.

The Operation: You can split any element nums[i] (where nums[i] > 1) into two smaller pieces of nums[i] / 2 each. For example, splitting 8 gives you two 4's.

Goal: Return the minimum operations needed so that you can select some elements from the array (a subsequence) that sum exactly to target. If impossible, return -1.

Example: If nums = [1, 2, 8] and target = 7, you could split 8 into two 4's, then split one 4 into two 2's, giving you [1, 2, 4, 2, 2]. Now you can pick [1, 2, 4] to sum to 7.

Input & Output

example_1.py โ€” Basic Case
$ Input: nums = [1, 2, 8], target = 7
โ€บ Output: 1
๐Ÿ’ก Note: We need to make 7. We have 1+2=3, but need 4 more. We can split 8 into two 4s (1 operation), then use 1+2+4=7.
example_2.py โ€” Multiple Operations
$ Input: nums = [1, 32], target = 12
โ€บ Output: 2
๐Ÿ’ก Note: Target 12 = 8+4. Split 32โ†’16,16 (1 op), then split 16โ†’8,8 (2 ops total). Now we have [1,8,8,16] and can use 8+4=12, but we need 4, so split another 8โ†’4,4 (3 ops total). Actually optimal is 2: split 32โ†’16,16, then 16โ†’8,8, use 8+4 where 4 comes from splitting 8โ†’4,4.
example_3.py โ€” Impossible Case
$ Input: nums = [1, 4], target = 6
โ€บ Output: -1
๐Ÿ’ก Note: Sum of nums is 5, which is less than target 6. No amount of splitting can increase the total sum, so it's impossible.

Constraints

  • 1 โ‰ค nums.length โ‰ค 1000
  • 1 โ‰ค nums[i] โ‰ค 230
  • nums[i] is a power of 2
  • 1 โ‰ค target โ‰ค 231 - 1

Visualization

Tap to expand
๐Ÿฆ Binary Bank Exchange๐Ÿ”น Your Wallet: [1๐Ÿ’ต, 2๐Ÿ’ต, 8๐Ÿ’ต] โ†’ Need: 7๐Ÿ’ตStep 1: Count bills โ†’ {1:1, 2:1, 8:1}Step 2: Target 7 = 111โ‚‚ (need 1ร—1๐Ÿ’ต + 1ร—2๐Ÿ’ต + 1ร—4๐Ÿ’ต)๐Ÿ”„ Exchange Process:1โœ“ Have 1๐Ÿ’ต, use it2โœ“ Have 2๐Ÿ’ต, use it4โŒ Need 4๐Ÿ’ต, but only have 8๐Ÿ’ต๐Ÿ’ก Break 8๐Ÿ’ต โ†’ 4๐Ÿ’ต + 4๐Ÿ’ต (1 operation)๐ŸŽฏ Result: 1 operation to make exact change!
Understanding the Visualization
1
Count Your Bills
First, count how many bills of each denomination you have
2
Process Target Bits
Look at each bit of the target amount from right to left
3
Make Change Greedily
For each bit, either use available bills or break larger ones
4
Count Operations
Each bill break costs one operation
Key Takeaway
๐ŸŽฏ Key Insight: Greedy works for powers of 2 because any larger denomination can always be broken into exactly what we need for smaller bits, without affecting the optimality of future decisions.
Asked in
Google 28 Amazon 22 Meta 18 Microsoft 15
28.4K Views
Medium Frequency
~25 min Avg. Time
892 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