Problem Description
Given an array of coins, determine the maximum number of consecutive integer values (starting from 0) that can be formed using any subset of these coins. A value x can be formed if some of the coins add up exactly to x.
Key Insights
- Sort the coins to process smaller values first.
- Maintain a running sum (denoted as maxReach) which represents the maximum consecutive value that can be formed so far.
- When processing a coin, if its value is greater than maxReach + 1, you cannot form maxReach + 1.
- Otherwise, add the coin's value to maxReach, extending the range of consecutively formable values.
Space and Time Complexity
Time Complexity: O(n log n) due to sorting the coins. Space Complexity: O(1) or O(n) depending on the sorting algorithm used.
Solution
The solution leverages a greedy approach. We first sort the coins. Then, we iterate through each coin while maintaining a variable (maxReach) which represents the highest consecutive value that can be formed. If a coin is greater than maxReach + 1, it indicates a gap, and we cannot form the next consecutive value. Otherwise, we extend maxReach by the coin's value. This approach ensures we cover every possible consecutive value until an unfillable gap is encountered.