KatInterview

Count Reachable Totals from a Bounded Coin Collection

Dynamic ProgrammingAuto-graded · 24 test cases
MediumAuto-gradedDynamic Programmingdynamic-programmingsubset-sumbounded-knapsack

Last updated

Count the distinct positive totals obtainable from a limited supply of coins per denomination, testing bounded subset-sum reachability with DP or bitset techniques.

Reachable Totals with Limited Coins

A wallet holds several kinds of coins. You are given two lists of equal length, values and quantities. For each index i, the wallet contains exactly quantities[i] coins, each worth values[i]. Coins of the same kind are indistinguishable, and a coin can be used at most once.

Choose any selection of coins from the wallet (using between 0 and quantities[i] coins of kind i). The total worth of the selection is its sum.

Return the number of distinct positive totals that can be produced this way.

Details:

  • A total counts once, no matter how many different selections produce it.
  • The total 0 (selecting nothing) is not counted.
  • Two entries may share the same value; they are treated as separate kinds, each with its own quantity.
  • An entry with quantity 0 contributes nothing.
  • If no positive total is possible (for example, empty lists or all quantities zero), return 0.

Your solution should remain efficient when quantities are large and the maximum possible total (the sum of values[i] * quantities[i]) is on the order of 10^6. Be ready to explain the time and space complexity of your approach.

Constraints

  • values and quantities have the same length n, with n >= 0.
  • values[i] > 0 for every i.
  • quantities[i] >= 0 for every i.
  • The maximum possible total sum(values[i] * quantities[i]) is at most about 10^6.
  • The function returns a single integer.

Examples

Example 1

Input: count_reachable_totals([1, 2, 5], [2, 2, 1])

Output: 11

Example 2

Input: count_reachable_totals([2, 3, 7], [1, 1, 1])

Output: 7

Example 3

Input: count_reachable_totals([1, 1, 3], [1, 1, 1])

Output: 5

Example 4

Input: count_reachable_totals([5, 10], [0, 2])

Output: 2

Hints

Hint 1

You only need to know which totals are reachable, not how many ways produce them, so a boolean table indexed by total is enough.

Hint 2

Treating each coin as its own 0/1 item is too slow for big quantities. Split a quantity c into chunks 1, 2, 4, ... and a remainder; any number from 0 to c is a sum of a subset of those chunks.

Hint 3

Process each chunk as a 0/1 item, updating totals from high to low (or use a big-integer bitset with `mask |= mask << weight`) so a chunk is never applied twice. Finally exclude total 0 when counting.