Maximum Number of Consecutive Values You Can Make - Problem

You are given an integer array coins of length n which represents the n coins that you own. The value of the ith coin is coins[i].

You can make some value x if you can choose some of your n coins such that their values sum up to x.

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

Note that you may have multiple coins of the same value.

Input & Output

Example 1 — Basic Case
$ Input: coins = [1,1,4]
Output: 3
💡 Note: You can make 0 (use no coins), 1 (use one coin), 2 (use both 1-coins), but cannot make 3. So consecutive values are [0,1,2] with count 3.
Example 2 — Single Coin
$ Input: coins = [1,3]
Output: 2
💡 Note: You can make 0 (no coins), 1 (use coin 1), but cannot make 2. The coin 3 is too large to fill the gap. Count = 2.
Example 3 — Larger Gap
$ Input: coins = [1,1,1,4]
Output: 8
💡 Note: With three 1's you can make [0,1,2,3]. Adding coin 4 extends to [0,1,2,3,4,5,6,7]. Count = 8.

Constraints

  • 1 ≤ coins.length ≤ 4 × 104
  • 1 ≤ coins[i] ≤ 4 × 104

Visualization

Tap to expand
Maximum Consecutive Values INPUT coins array: 1 i=0 1 i=1 4 i=2 coins = [1, 1, 4] n = 3 coins Goal: max consecutive from 0 Coin Values: 1 1 4 ALGORITHM STEPS 1 Sort coins [1,1,4] --> [1,1,4] 2 Init reach = 0 Can make [0..reach] 3 Greedy extend If coin <= reach+1: extend 4 Return reach+1 Count of values [0..reach] Iteration Trace: coin=1: 1<=0+1 OK reach: 0 --> 1 coin=1: 1<=1+1 OK reach: 1 --> 2 coin=4: 4>2+1 STOP FINAL RESULT Consecutive values from 0: 0 1 2 [OK] Can make these values 3 Cannot make 3 How values are made: 0: use no coins 1: use coin[0]=1 2: use coin[0]+coin[1]=1+1 Output: 3 Key Insight: If we can make all values [0..reach], and next sorted coin <= reach+1, then we can extend to [0..reach+coin]. Otherwise, reach+1 is impossible. Time: O(n log n) for sorting. Space: O(1) extra. TutorialsPoint - Maximum Number of Consecutive Values You Can Make | Greedy Optimal Solution
Asked in
Google 15 Amazon 12 Microsoft 8 Meta 6
24.5K Views
Medium Frequency
~25 min Avg. Time
847 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