1760. First Greedy Failure
A vending machine pays out change using coin denominations given in the array coins. The denominations are distinct, sorted in strictly increasing order, and always include a coin of value 1, so every amount can be paid. The machine uses a simple habit: while some amount remains, it hands out the largest coin that does not exceed what is left. For some denomination sets this habit uses more coins than necessary.
Return the smallest positive amount for which the habit hands out strictly more coins than the true minimum, or -1 if the habit is optimal for every amount. When coins has at most two entries the answer is always -1. Hint: if a failing amount exists, one exists below coins[n-2] + coins[n-1], so a bounded min-coin table is enough. Aim for O(n * (coins[n-2] + coins[n-1])) time and O(coins[n-2] + coins[n-1]) space.
Example 1
- Input:
- coins = [1,3,4]
- Output:
- 6
- Explanation:
For amount 6 the habit pays 4+1+1 (three coins) while 3+3 needs only two, and every smaller amount is paid optimally.
Example 2
- Input:
- coins = [1,5,10,25]
- Output:
- -1
- Explanation:
For this denomination set the largest-coin habit is optimal for every amount, so the answer is -1.
Example 3
- Input:
- coins = [1,5,8]
- Output:
- 10
- Explanation:
Amount 10 costs 8+1+1 (three coins) by the habit but 5+5 (two coins) optimally; no smaller amount fails.
Constraints
1 ≤ n ≤ 30, where n = coins.length
coins[0] = 1, coins is strictly increasing, coins[i] ≤ 104
How this problem is judged
- Answers
- Your answer must match exactly. Numbers compare by value, so 2 and 2.0 are equal.
- Time per case
- Python 2,000 msC++ 500 msJava 1,000 msJavaScript 1,000 msTypeScript 1,000 ms
Expected complexity
- Time
- O(n * (coins[n-2] + coins[n-1]))
- Space
- O(coins[n-2] + coins[n-1])