Bag of Tokens — LeetCode 948 Python Solution
- Problem
- #948
- Pattern
- Two Pointers
- Reading time
- 3 min
- Source
- leetcode.com
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
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 ansComplexity
| Measure | Complexity |
|---|---|
| Time | O(n \log n) |
| Space | O(\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.