Ctrl K

Break Coins for an Exact Payment

Hard
Your wallet holds coins coins, and every denomination is a power of two. You need to pay exactly amount by picking some of the coins, with no change given. In one operation you may break a coin worth more than 1 into two coins of half its value. Return the fewest breaks after which some coins in the wallet add up to exactly amount. If that is impossible, return -1.
Example 1
coins=[1, 4], amount=3 → 1

Break the 4 into two 2s and pay 1 + 2 = 3. One break is enough.

Example 2
coins=[16], amount=3 → 4

16 → 8 + 8, then 8 → 4 + 4, 4 → 2 + 2 and 2 → 1 + 1. After four breaks you hold a 2 and a 1.

Example 3
coins=[2, 2], amount=5 → -1

There is only 4 in total and breaking coins never changes the total.

Constraints
  • 1 ≤ len(coins) ≤ 1000
  • 1 ≤ coins[i] ≤ 2³⁰, and coins[i] is a power of two
  • 1 ≤ amount < 2³¹
Have you seen this problem in a real interview?
Solved by0
Tried by0
Submissions0
Acceptance—
Topics
Similar problemsShifting Bits for Bigger Squares HardMerge Neighbors for a Small OR HardEdge Toggles on a Tree HardBest Binary Rows After Flips MediumGroups of Four at the Cinema Medium
loading Python…
Input
coins=[1, 4], amount=3
Expected
1

Run checks the first 3 tests in your browser. Submit checks all 118 tests on the server, hidden ones included.