LeetCode 948, Medium. Topics: Array, Two Pointers, Greedy, Sorting. View on LeetCode.
Generate this problem as a practice environment: tested reference solution, 15 parametrized pytest cases, and a playground notebook:
Problem
<p>You start with an initial power of <code>power</code>, an initial score of <code>0</code>, and a bag of tokens given as an integer array <code>tokens</code>, where each <code>tokens[i]</code> denotes the value of token<sub>i</sub>.</p>
<p>Your goal is to maximize the total <strong>score</strong> by strategically playing these tokens. In one move, you can play an <strong>unplayed</strong> token in one of the two ways (but not both for the same token):</p>
<ul>
<li><strong>Face-up:</strong> If your current power is at least <code>tokens[i]</code>, you may play token<sub>i</sub>, losing <code>tokens[i]</code> power and gaining <code>1</code> score.</li>
<li><strong>Face-down:</strong> If your current score is at least <code>1</code>, you may play token<sub>i</sub>, gaining <code>tokens[i]</code> power and losing <code>1</code> score.</li>
</ul>
<p>Return <em>the maximum possible <strong>score</strong> you can achieve after playing any number of tokens</em>.</p>
Examples
Constraints
- 0 <= tokens.length <= 1000
- 0 <= tokens[i], power < 10^4
Solution
Reference implementation from solution.py on GitHub, full suite in test_solution.py:
Complexity
NeetCode All. Last modified on September 7, 2026