Bag of Tokens - Problem
Bag of Tokens - A Strategic Power and Score Management Problem

You're a strategic game player starting with an initial power value and a score of 0. You have a bag containing various tokens, each with a specific power value represented in the array tokens.

Your objective is to maximize your final score by strategically playing these tokens in one of two ways:

πŸ”₯ Face-Up Play: If your current power β‰₯ tokens[i], you can spend tokens[i] power to gain 1 score point

πŸ’° Face-Down Play: If your current score β‰₯ 1, you can spend 1 score point to gain tokens[i] power

Each token can only be played once, and you must choose the optimal sequence of moves to achieve the maximum possible score.

Input & Output

example_1.py β€” Basic Token Strategy
$ Input: tokens = [100,200,300,400], power = 200
β€Ί Output: 2
πŸ’‘ Note: Play token 100 face-up (power=100, score=1), play token 400 face-down (power=500, score=0), play token 200 face-up (power=300, score=1), play token 300 face-up (power=0, score=2). Maximum score is 2.
example_2.py β€” Insufficient Power
$ Input: tokens = [100,200], power = 150
β€Ί Output: 1
πŸ’‘ Note: Play token 100 face-up (power=50, score=1). Cannot play token 200 face-up due to insufficient power, and cannot play face-down since we need scoreβ‰₯1. Maximum score is 1.
example_3.py β€” Empty Tokens
$ Input: tokens = [], power = 85
β€Ί Output: 0
πŸ’‘ Note: No tokens available to play, so the maximum score remains 0.

Constraints

  • 0 ≀ tokens.length ≀ 1000
  • 0 ≀ tokens[i], power < 104
  • Each token can only be used once
  • Score starts at 0 and power is given as input

Visualization

Tap to expand
Strategic Token ManagementGreedy Two-Pointer ApproachInitial StatePower: 200Score: 0Tokens: [100,200,300,400]STEP 1Face-Up: 100Power: 100Score: 1STEP 2Face-Down: 400Power: 500Score: 0STEP 3Face-Up: 200Power: 300Score: 1STEP 4Face-Up: 300Power: 0Score: 2Greedy Strategy VisualizationFace-Up (Gain Score):Use smallest tokens for efficiencyFace-Down (Gain Power):Use largest tokens for maximum returnResult:Maximum possible score achievedFinal Answer: 2Time: O(n log n) | Space: O(1)
Understanding the Visualization
1
Sort by Value
Arrange tokens from cheapest to most expensive
2
Greedy Face-Up
Always buy points using the cheapest available tokens
3
Strategic Face-Down
When power is low but you have points, sell a point for maximum power using the most expensive token
4
Track Maximum
Keep track of the highest score achieved throughout the process
Key Takeaway
🎯 Key Insight: Sort tokens and use greedy strategy - cheapest for scoring, most expensive for power recovery. This maximizes efficiency at each step.
Asked in
Google 45 Amazon 38 Meta 25 Microsoft 22
73.9K Views
Medium Frequency
~15 min Avg. Time
1.8K 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