Skip to content

3116. Kth Smallest Amount With Single Denomination Combination 👍

  • Time: $O(2^{|\texttt{coins}|} \cdot \log k)$
  • Space: $O(2^{|\texttt{coins}|})$
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
class Solution {
 public:
  long long findKthSmallest(vector<int>& coins, int k) {
    const vector<vector<long>> sizeToLcms = getSizeToLcms(coins);
    long l = 0;
    long r = static_cast<long>(k) * ranges::min(coins);

    while (l < r) {
      const long m = (l + r) / 2;
      if (numDenominationsNoGreaterThan(sizeToLcms, m) >= k)
        r = m;
      else
        l = m + 1;
    }

    return l;
  }

 private:
  // Returns the number of denominations <= m.
  long numDenominationsNoGreaterThan(const vector<vector<long>>& sizeToLcms,
                                     long m) {
    long res = 0;
    for (int sz = 1; sz < sizeToLcms.size(); ++sz)
      for (const long lcm : sizeToLcms[sz])
        // Principle of Inclusion-Exclusion (PIE)
        res += m / lcm * pow(-1, sz + 1);
    return res;
  };

  // Returns the LCMs for each number of combination of coins.
  vector<vector<long>> getSizeToLcms(const vector<int>& coins) {
    const int n = coins.size();
    const int maxMask = 1 << n;
    vector<vector<long>> sizeToLcms(n + 1);

    for (unsigned mask = 1; mask < maxMask; ++mask) {
      long lcmOfSelectedCoins = 1;
      for (int i = 0; i < n; ++i)
        if (mask >> i & 1)
          lcmOfSelectedCoins = lcm(lcmOfSelectedCoins, coins[i]);
      sizeToLcms[popcount(mask)].push_back(lcmOfSelectedCoins);
    }

    return sizeToLcms;
  }
};
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
class Solution {
  public long findKthSmallest(int[] coins, int k) {
    List<Long>[] sizeToLcms = getSizeToLcms(coins);
    long l = 0;
    long r = (long) k * Arrays.stream(coins).min().getAsInt();

    while (l < r) {
      final long m = (l + r) / 2;
      if (numDenominationsNoGreaterThan(sizeToLcms, m) >= k)
        r = m;
      else
        l = m + 1;
    }

    return l;
  }

  // Returns the number of denominations <= m.
  private long numDenominationsNoGreaterThan(List<Long>[] sizeToLcms, long m) {
    long res = 0;
    for (int sz = 1; sz < sizeToLcms.length; ++sz)
      for (long lcm : sizeToLcms[sz])
        res += m / lcm * Math.pow(-1, sz + 1);
    return res;
  }

  // Returns the LCMs for each number of combination of coins.
  private List<Long>[] getSizeToLcms(int[] coins) {
    final int n = coins.length;
    final int maxMask = 1 << n;
    List<Long>[] sizeToLcms = new List[n + 1];

    for (int i = 1; i <= n; ++i)
      sizeToLcms[i] = new ArrayList<>();

    for (int mask = 1; mask < maxMask; ++mask) {
      long lcmOfSelectedCoins = 1;
      for (int i = 0; i < n; ++i)
        if ((mask >> i & 1) == 1)
          lcmOfSelectedCoins = lcm(lcmOfSelectedCoins, coins[i]);
      sizeToLcms[Integer.bitCount(mask)].add(lcmOfSelectedCoins);
    }

    return sizeToLcms;
  }

  private long lcm(long a, long b) {
    return a * b / gcd(a, b);
  }

  private long gcd(long a, long b) {
    return b == 0 ? a : gcd(b, a % b);
  }
}
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
class Solution:
  def findKthSmallest(self, coins: list[int], k: int) -> int:
    sizeToLcms = self._getSizeToLcms(coins)

    def count(m: int) -> int:
      """Returns the number of denominations <= m."""
      res = 0
      for sz, lcms in enumerate(sizeToLcms):
        for lcm in lcms:
          # Principle of Inclusion-Exclusion (PIE)
          res += m // lcm * pow(-1, sz + 1)
      return res

    return bisect.bisect_left(range(k * min(coins)), k,
                              key=lambda m: count(m))

  def _getSizeToLcms(self, coins: list[int]) -> list[list[int]]:
    # Returns the LCMs for each number of combination of coins.
    sizeToLcms = [[] for _ in range(len(coins) + 1)]
    for sz in range(1, len(coins) + 1):
      for combination in itertools.combinations(coins, sz):
        sizeToLcms[sz].append(math.lcm(*combination))
    return sizeToLcms