Kth Smallest Amount With Single Denomination Combination Problem
Description
LeetCode Problem 3116.
You are given an integer array coins representing coins of different denominations and an integer k.
You have an infinite number of coins of each denomination. However, you are not allowed to combine coins of different denominations.
Return the k^th smallest amount that can be made using these coins.
Example 1:
Input: coins = [3,6,9], k = 3
Output: 9
Explanation: The given coins can make the following amounts:
Coin 3 produces multiples of 3: 3, 6, 9, 12, 15, etc.
Coin 6 produces multiples of 6: 6, 12, 18, 24, etc.
Coin 9 produces multiples of 9: 9, 18, 27, 36, etc.
All of the coins combined produce: 3, 6, 9, 12, 15, etc.
Example 2:
Input: coins = [5,2], k = 7
Output: 12
Explanation: The given coins can make the following amounts:
Coin 5 produces multiples of 5: 5, 10, 15, 20, etc.
Coin 2 produces multiples of 2: 2, 4, 6, 8, 10, 12, etc.
All of the coins combined produce: 2, 4, 5, 6, 8, 10, 12, 14, 15, etc.
Constraints:
1 <= coins.length <= 151 <= coins[i] <= 251 <= k <= 2 * 10^9coinscontains pairwise distinct integers.
Solution
Approach: Binary Search + Inclusion-Exclusion
The count of reachable amounts that are at most x never decreases as x grows, so binary search the smallest x whose count is at least k.
To count amounts up to x, add up the multiples of each coin and fix the double counting with inclusion-exclusion: for every non-empty subset of coins, take x / lcm(subset), adding it when the subset size is odd and subtracting it when even. With at most 15 coins there are at most 2^15 subsets, enumerated with a bitmask. The lcm can stop growing once it exceeds x, since that term is then zero.
Search between 1 and 10^11.
Complexity: O(n 2^n log(kM)) time, where n is the number of coins and M the largest coin.
from math import gcd
class Solution:
def findKthSmallest(self, coins: List[int], k: int) -> int:
n = len(coins)
lcms = [1] * (1 << n)
sign = [1] * (1 << n)
for i in range(1, 1 << n):
low = (i & -i).bit_length() - 1
rest = i & (i - 1)
a = lcms[rest]
b = coins[low]
lcms[i] = min(a // gcd(a, b) * b, 10**12)
sign[i] = -sign[rest]
def check(mx: int) -> bool:
cnt = 0
for i in range(1, 1 << n):
cnt -= sign[i] * (mx // lcms[i])
return cnt >= k
l, r = 1, 10**11
while l < r:
mid = (l + r) >> 1
if check(mid):
r = mid
else:
l = mid + 1
return l