Bag of Tokens (LeetCode 948): Solution and Explanation
Spend power on tokens to gain score, or trade score back for power, and return the highest score you can reach.
Intuition
Every face-up play earns exactly one point, no matter which token it uses. So when buying a point, the cheapest unplayed token is always the right one.
Every face-down play costs exactly one point. So when you need power, sell that point for the most expensive unplayed token.
After sorting, the cheap tokens are on the left and the rich ones on the right, so two pointers moving inward model the whole game. Because a trade can lower the score for a while, remember the best score seen at any moment.
Approach: Sort, then greedy two pointers
- Sort tokens ascending and set lo = 0, hi = n - 1, score = best = 0.
- While lo <= hi: if power >= tokens[lo], pay tokens[lo], move lo right, add 1 to score and update best.
- Otherwise, if score > 0 and lo < hi, gain tokens[hi] power, move hi left and subtract 1 from score.
- Otherwise no move helps, so stop. Return best.
Step-by-step example
tokens = [100,200,300,400], power = 200
- Sorted tokens: [100,200,300,400], lo = 0, hi = 3.
- Power 200 covers 100: play it face up. Power 100, score 1, best 1.
- Power 100 cannot pay for 200, so sell a point for 400 face down. Power 500, score 0.
- Play 200 face up: power 300, score 1.
- Play 300 face up: power 0, score 2, best 2. lo passes hi, so return 2.
Code: Python, Java, C++
1class Solution:
2 def bagOfTokensScore(self, tokens: List[int], power: int) -> int:
3 tokens.sort()
4 lo, hi = 0, len(tokens) - 1
5 score = best = 0
6 while lo <= hi:
7 if power >= tokens[lo]:
8 power -= tokens[lo]
9 lo += 1
10 score += 1
11 best = max(best, score)
12 elif score > 0 and lo < hi:
13 power += tokens[hi]
14 hi -= 1
15 score -= 1
16 else:
17 break
18 return best1class Solution {
2 public int bagOfTokensScore(int[] tokens, int power) {
3 Arrays.sort(tokens);
4 int lo = 0, hi = tokens.length - 1;
5 int score = 0, best = 0;
6 while (lo <= hi) {
7 if (power >= tokens[lo]) {
8 power -= tokens[lo++];
9 score++;
10 best = Math.max(best, score);
11 } else if (score > 0 && lo < hi) {
12 power += tokens[hi--];
13 score--;
14 } else {
15 break;
16 }
17 }
18 return best;
19 }
20}1class Solution {
2public:
3 int bagOfTokensScore(vector<int>& tokens, int power) {
4 sort(tokens.begin(), tokens.end());
5 int lo = 0, hi = (int)tokens.size() - 1;
6 int score = 0, best = 0;
7 while (lo <= hi) {
8 if (power >= tokens[lo]) {
9 power -= tokens[lo++];
10 score++;
11 best = max(best, score);
12 } else if (score > 0 && lo < hi) {
13 power += tokens[hi--];
14 score--;
15 } else {
16 break;
17 }
18 }
19 return best;
20 }
21};Time and space complexity
O(n log n)
Sorting dominates. The two-pointer pass plays each token at most once, which is O(n).
O(1)
Only the pointers, power, score and best, beyond what the sort uses.
Other approaches
Deque of sorted tokens (time O(n log n), space O(n))
Put the sorted tokens in a deque, pop from the front for face-up plays and from the back for face-down plays. Same logic, slightly more memory.
Try every order (time O(2^n * n), space O(2^n))
Search all sequences of plays with memoization on the set of used tokens. Correct, but exponential in the number of tokens.
Common mistakes
- Returning the final score instead of the best score seen; a late face-down play can lower it.
- Selling the last remaining token face down (lo == hi). It loses a point and no token is left to buy it back.
- Forgetting the empty bag, where the answer is simply 0.
Frequently asked questions
Why is buying with the smallest token optimal?
Any face-up play gives the same single point, so using the cheapest token leaves the most power for later. Swapping a more expensive face-up token for a cheaper one never makes a sequence worse.
Why sell the largest token?
A face-down play always costs one point, so it should return as much power as possible. The largest token does that, and it is also the one you are least likely to afford face up.
Why track best instead of returning score?
The loop may end right after a face-down trade that never got used. Keeping the maximum score seen covers that case.
Is the play order inside the loop important?
Yes. Try face up first, because it raises the score directly. Only trade a point for power when you cannot afford the cheapest token.