Bag of Tokens

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<sub>i</sub>. 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<sub>i</sub>, losing `tokens[i]` power and gaining `1` score. - **Face-down**: If your current score is **at least** `1`, you may play token<sub>i</sub>, gaining `tokens[i]` power and losing `1` score. Return *the **maximum** possible score you can achieve after playing **any** number of tokens*.

30:00

Bag of Tokens
medium
Free written solution
Topics
Companies

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 tokeni.

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 tokeni, losing tokens[i] power and gaining 1 score.
  • Face-down: If your current score is at least 1, you may play tokeni, gaining tokens[i] power and losing 1 score.

Return the maximum possible score you can achieve after playing any number of tokens.

Example 1:
Input: {"tokens":[100],"power":50}
Output: 0
Constraints:
  • 0≤tokens.length≤10000 \leq \text{tokens.length} \leq 1000

  • 0≤tokens[i],power<1040 \leq \text{tokens}[i], \text{power} < 10^4

Test Cases
Input (Stdin)
Expected Output (Stdout)
Execution Result

Run code to see results.

Input
arr ={"tokens":[100],"power":50}

Power starts at 50 and score at 0. A face-up play buys 1 score with power; a face-down play sells 1 score for power.

tokens (unsorted)

100

power

50

score

no score yet

power

50

score

0

best

0

up / down

0 / 0

face up: -power, +1 score
face down: +power, -1 score
lo / hi pointers
best score (hollow dots)
Variables
VariableValue
lo0
hi0
power50
score0
best0
DepthFunction Call
Stack empty
0/3