Bag of Tokens — LeetCode 948 Python Solution

MediumGreedyArrayTwo PointersSorting
Problem
#948
Reading time
3 min

The problem

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.

Python solution

Python
class Solution:
    def bagOfTokensScore(self, tokens: List[int], power: int) -> int:
        tokens.sort()
        ans = score = 0
        i, j = 0, len(tokens) - 1
        while i <= j:
            if power >= tokens[i]:
                power -= tokens[i]
                score, i = score + 1, i + 1
                ans = max(ans, score)
            elif score:
                power += tokens[j]
                score, j = score - 1, j - 1
            else:
                break
        return ans

Complexity

MeasureComplexity
TimeO(n \log n)
SpaceO(\log n) auxiliary

Pattern: Two Pointers

Use the order already in the input to discard half the search space at every step. LeetCode 948. Bag of Tokens is filed here because LeetCode tags it Two Pointers, which is the vocabulary this hub collects.

The two pointers guide has the Python template for the pattern and the 201 LeetCode problems that use it.

Related problems

Frequently asked questions

How hard is LeetCode 948. Bag of Tokens?
LeetCode 948. Bag of Tokens is rated Medium on LeetCode.
What is the time complexity of LeetCode 948. Bag of Tokens?
The Python solution on this page runs in O(n \log n).
What is the space complexity of LeetCode 948. Bag of Tokens?
The Python solution on this page uses O(\log n) auxiliary space.
What topics does LeetCode 948. Bag of Tokens cover?
LeetCode 948. Bag of Tokens is tagged Greedy, Array, Two Pointers and Sorting on LeetCode.

Stuck on problems like this in a live interview?

Stealth Interview is a desktop app for macOS and Windows. It reads the problem off your screen and returns a working solution with a step-by-step explanation and its time and space complexity — invisible to screen sharing.

Get Stealth Interview