Payments app~15 min2s · 256 MBtarget O(n log n) time, O(n) spaceclassic twin: lc-948greedy · sorting
You work on a payments app with a rewards game. A player holds credits and a bag of reward tokens, each with a face value in credits. Each token can be used once, in one of two ways.
Redeeming a token costs its value in credits and adds 1 point. Cashing in a token adds its value in credits and costs 1 point, so it needs at least 1 point. Your team lead asks: "What is the highest score a player can reach?"
Write best_score(tokens, credits).
credits credits and a score of 0.i: allowed when the credits are at least tokens[i]. It subtracts tokens[i] from the credits and adds 1 to the score.i: allowed when the score is at least 1. It adds tokens[i] to the credits and subtracts 1 from the score.Input: tokens = [5, 9, 2, 14], credits = 6
Output: 2Sort the tokens: 2, 5, 9, 14. Redeem the cheapest token when the credits allow it. When they do not, and there is a point to give, cash in the dearest token.
| Action | Token | Credits | Score |
|---|---|---|---|
| Start | 6 | 0 | |
| Redeem the cheapest | 2 | 4 | 1 |
| Cash in the dearest (5 costs more than 4) | 14 | 18 | 0 |
| Redeem the cheapest | 5 | 13 | 1 |
| Redeem the cheapest | 9 | 4 | 2 |
No tokens are left. The highest score reached is 2.
Input: tokens = [10], credits = 5
Output: 0The only token costs 10, and the player has 5. There is no point to give for a cash-in, so the score stays 0.
Input: tokens = [3, 3, 3], credits = 7
Output: 2Redeem two tokens for 6 credits and reach 2 points. The third token costs 3, and 1 credit is left.
0 ≤ len(tokens) ≤ 100,0001 ≤ tokens[i] ≤ 1,000,000,0000 ≤ credits ≤ 1,000,000,000There can be 100,000 tokens. Trying every order and every action for each token is n! times 2^n possibilities. A sort costs about 1.7 million steps and one pass costs 100,000 more. Credits can grow to about 10^14, so use a 64-bit number.