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: Sort tokens to [100,200,300,400]. Play 100 face-up (power=100, score=1). Can't play 200 face-up with remaining power, so play 400 face-down (power=500, score=0). Now play 200 face-up (power=300, score=1) and 300 face-up (power=0, score=2). Maximum achievable score is 2.
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
Bag of Tokens - Greedy Two Pointers INPUT tokens[] (sorted for greedy) 100 i=0 200 i=1 300 i=2 400 i=3 left right Power 200 Score 0 Token Strategies: Face-up: Spend power ---> Gain 1 score Face-down: Spend 1 score ---> Gain power ALGORITHM STEPS 1 Sort tokens array Smallest first for efficiency 2 Play face-up (left ptr) If power >= token[left] 3 Play face-down (right) If score >= 1, gain power 4 Track max score Update best result Simulation: Step Action Power Score 1 +100 up 100 1 2 +400 dn 500 0 3 +200 up 300 1 4 +300 up 0 2 FINAL RESULT Maximum Score Achieved 2 Output: maxScore = 2 Tokens Played: 100 Face-up 200 Face-up 300 Face-up 400 Face-dn Time Complexity O(n log n) Key Insight: Greedy strategy: Always play the SMALLEST token face-up (minimize power loss) and LARGEST token face-down (maximize power gain). Sort array, use two pointers from both ends. Only sacrifice score for power when you can't afford any more face-up plays. TutorialsPoint - Bag of Tokens | Greedy with Two Pointers Approach
Asked in
Google 15 Amazon 12 Microsoft 8 Facebook 6
23.4K Views
Medium Frequency
~25 min Avg. Time
856 Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen