> ## Documentation Index
> Fetch the complete documentation index at: https://leetcode-py.wisl.dev/llms.txt
> Use this file to discover all available pages before exploring further.

> ## Agent Instructions
> leetcode-py is a Python LeetCode practice environment generator with one CLI: lcpy. It is not a service or platform.
> Each problem is a directory under leetcode/ with README.md, solution.py, test_solution.py, helpers.py, and playground.ipynb. lcpy gen creates them from JSON templates bundled with the package.
> Examples are backed by tests; copy them verbatim.

# Bag of Tokens Python Solution with Tests

> Tested Python solution for LeetCode 948 with 15 pytest cases. Generate a practice environment with lcpy.

LeetCode 948, [Medium](/catalog/medium). Topics: [Array](/catalog/topics/array), [Two Pointers](/catalog/topics/two-pointers), [Greedy](/catalog/topics/greedy), [Sorting](/catalog/topics/sorting). [View on LeetCode](https://leetcode.com/problems/bag-of-tokens/description/).

Generate this problem as a practice environment: tested reference solution, 15 [parametrized pytest cases](/practice/testing), and a playground notebook:

```bash theme={"theme":{"light":"github-light","dark":"github-dark"}}
lcpy gen -n 948   # by problem number
lcpy gen -s bag_of_tokens   # by problem name
```

## 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

```
Input: tokens = [100], power = 50
Output: 0
Explanation: Since your score is 0 initially, you cannot play the token face-down. You also cannot play it face-up since your power (50) is less than tokens[0] (100).
```

```
Input: tokens = [200,100], power = 150
Output: 1
Explanation: Play token1 (100) face-up, reducing your power to 50 and increasing your score to 1.
```

```
Input: tokens = [100,200,300,400], power = 200
Output: 2
Explanation: Play the tokens in this order to get a score of 2:
Play token0 (100) face-up, reducing power to 100 and increasing score to 1.
Play token3 (400) face-down, increasing power to 500 and reducing score to 0.
Play token1 (200) face-up, reducing power to 300 and increasing score to 1.
Play token2 (300) face-up, reducing power to 0 and increasing score to 2.
```

### Constraints

* 0 \<= tokens.length \<= 1000
* 0 \<= tokens\[i], power \< 10^4

## Solution

Reference implementation from [solution.py on GitHub](https://github.com/wislertt/leetcode-py/blob/main/leetcode/bag_of_tokens/solution.py), full suite in [test\_solution.py](https://github.com/wislertt/leetcode-py/blob/main/leetcode/bag_of_tokens/test_solution.py):

```python theme={"theme":{"light":"github-light","dark":"github-dark"}}
class Solution:
    # Time: O(n log n)
    # Space: O(n) for the sorted copy
    def bag_of_tokens_score(self, tokens: list[int], power: int) -> int:
        tokens = sorted(tokens)
        left, right = 0, len(tokens) - 1
        score = 0
        best = 0
        while left <= right:
            if power >= tokens[left]:
                # Cheapest token face-up for score
                power -= tokens[left]
                left += 1
                score += 1
                best = max(best, score)
            elif score >= 1:
                # Most expensive token face-down for power
                power += tokens[right]
                right -= 1
                score -= 1
            else:
                break
        return best
```

## Complexity

| Time | Space |
| - | - |
| O(n log n) | O(n) for the sorted copy |

## Tags

[NeetCode All](/catalog/neetcode).


This documentation is built and hosted on [Mintlify](https://mintlify.com), a developer documentation platform.