Bag of Tokens - Problem
Bag of Tokens - A Strategic Power and Score Management Problem
You're a strategic game player starting with an initial
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 β₯
π° Face-Down Play: If your current score β₯ 1, you can spend 1 score point to gain
Each token can only be played once, and you must choose the optimal sequence of moves to achieve the maximum possible score.
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] powerEach 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
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.
π‘
Explanation
AI Ready
π‘ Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code