Maximum Number of Consecutive Values You Can Make - Problem

Imagine you're running a small coin exchange and want to know the maximum range of consecutive values you can make starting from 0 using your available coins.

You are given an integer array coins of length n representing the coins you own. The value of the i-th coin is coins[i]. You can make some value x if you can choose any subset of your coins such that their values sum up to x.

Goal: Return the maximum number of consecutive integer values that you can make with your coins starting from and including 0.

Note: You may have multiple coins of the same value, and you don't need to use all coins to make a value.

Example: If you have coins [1, 3], you can make values: 0 (no coins), 1 (coin 1), 3 (coin 3), and 4 (coins 1+3). Since you can make 0, 1 but not 2, the answer is 2.

Input & Output

example_1.py โ€” Basic Case
$ Input: [1, 3]
โ€บ Output: 2
๐Ÿ’ก Note: You can make 0 (no coins) and 1 (using coin 1), but you cannot make 2. The next consecutive value would be 2, so the answer is 2.
example_2.py โ€” Multiple Small Coins
$ Input: [1, 1, 1, 4]
โ€บ Output: 8
๐Ÿ’ก Note: You can make 0, 1, 2, 3 (using 1+1+1), 4, 5 (1+4), 6 (1+1+4), and 7 (1+1+1+4). You cannot make 8, so the answer is 8.
example_3.py โ€” Large Gap
$ Input: [1, 4, 10, 3, 1]
โ€บ Output: 20
๐Ÿ’ก Note: After sorting: [1,1,3,4,10]. We can make consecutive values 0 through 19. Adding 1: [0,1], adding 1: [0,1,2], adding 3: [0,1,2,3,4,5], adding 4: [0-9], adding 10: [0-19]. Cannot make 20.

Constraints

  • 1 โ‰ค coins.length โ‰ค 4 ร— 104
  • 1 โ‰ค coins[i] โ‰ค 4 ร— 104
  • Each coin has a positive integer value

Visualization

Tap to expand
Building Consecutive Values: [1,1,4] ExampleInitial State:0Can make: {0}reachable = 0Add first coin (1):01Can make: {0,1}reachable = 1Add second coin (1):012Can make: {0,1,2}reachable = 2Try to add coin (4):0123Gap! 4 > 2+1Final Answer:3 values๐Ÿ”‘ Key InsightIf we can make all values [0...h]and coin โ‰ค h+1, then adding thiscoin extends our range to [0...h+coin]Why? We can make h+1, h+2, ..., h+coinby adding coin to values 1, 2, ..., coin
Understanding the Visualization
1
Sort the Coins
Arrange coins from smallest to largest to process optimally
2
Track Reachable Range
Keep track of the maximum consecutive sum we can achieve so far
3
Extend or Stop
For each coin, either extend the range or detect a gap
4
Return Count
Return the total count of consecutive values we can make
Key Takeaway
๐ŸŽฏ Key Insight: The greedy approach works because if we can make [0...h] consecutively and have a coin โ‰ค h+1, we can always extend to [0...h+coin] without gaps.
Asked in
Google 45 Amazon 38 Meta 28 Microsoft 22
42.5K Views
Medium-High Frequency
~22 min Avg. Time
1.3K 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