Bag of Tokens - Problem
You start with an initial power of power, an initial score of 0, and a bag of tokens given as an integer array tokens, where each tokens[i] denotes the value of token i.
Your goal is to maximize the total score by strategically playing these tokens. In one move, you can play an unplayed token in one of the two ways (but not both for the same token):
Face-up: If your current power is at least tokens[i], you may play token i, losing tokens[i] power and gaining 1 score.
Face-down: If your current score is at least 1, you may play token i, gaining tokens[i] power and losing 1 score.
Return the maximum possible score you can achieve after playing any number of tokens.
Input & Output
Example 1 — Basic Strategy
$
Input:
tokens = [100,200,300,400], power = 200
›
Output:
2
💡 Note:
Play token 100 face-up (power becomes 100, score becomes 1), then play token 200 face-up (power becomes -100, but we had enough initially), so we can get score 2 by playing tokens 100 and 200 face-up when we had enough power.
Example 2 — Face-down Strategy
$
Input:
tokens = [100], power = 50
›
Output:
0
💡 Note:
We don't have enough power (50) to play the token (100) face-up, and we don't have any score to play it face-down, so maximum score is 0.
Example 3 — Mixed Strategy
$
Input:
tokens = [200,100], power = 150
›
Output:
1
💡 Note:
Sort tokens to [100,200]. Play token 100 face-up (power becomes 50, score becomes 1). We can't play 200 face-up as we don't have enough power, so max score is 1.
Constraints
- 0 ≤ tokens.length ≤ 1000
- 0 ≤ tokens[i], power < 104
Visualization
Tap to expand
Understanding the Visualization
1
Input
tokens = [100,200,300,400], power = 200
2
Strategy
Sort tokens and use two pointers for optimal play
3
Output
Maximum possible score = 2
Key Takeaway
🎯 Key Insight: Sort tokens first, then greedily play cheapest face-up and most expensive face-down for optimal score
💡
Explanation
AI Ready
💡 Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code