Problem 948

Abstract / Summary

You can gain points by playing tokens against power, choosing to play or skip each turn.

Note

The full problem description, including helpful examples, can be found on LeetCode.

Python 0948.py

class Solution:
    def bagOfTokensScore(self, tokens: List[int], power: int) -> int:
        result = 0

        tokens.sort()
        score = 0
        left  = 0
        right = len(tokens) - 1
        while left <= right:
            # smallest token: face-up
            if tokens[left] <= power:
                power -= tokens[left]
                left  += 1
                score += 1
                result = max(result, score)
                continue

            # largest token: face-down
            if score > 0:
                power += tokens[right]
                right -= 1
                score -= 1
                continue

            break # no token possible

        return result
27 lines | 735 bytes | submitted February 28, 2024 | GitHub   14% comment ratio | tab size 4 | low complexity

Difficulty

This problem is ranked as
easy medium hard

and has an acceptance rate of about 60% (400k+ submissions).

Typical patterns to solve this problem:
  • Array
  • Greedy
  • Sorting
  • Two Pointers
I solved 663 easy, 1250 medium and 309 hard problems

AI Disclaimer

Every single line of code was written by me, 100% from scratch, between August 2023 and August 2024.
However, two years later I set up this website and used various AI tools to generate most of the walkthrough / explanations below.

See this dedicated page for more details.
LeetCode profile | GitHub repo

Code Walkthrough

Overview

The bagOfTokensScore method computes the maximum score achievable by playing a game with a list of token values and an initial amount of power. Tokens can be played in two ways: a face-up move consumes power equal to the token’s value and increases the score by one, while a face-down move consumes one point of score, restores power equal to the token’s value, and removes the token from consideration. The algorithm seeks the highest score reachable through any sequence of these moves.

Key Steps

Sorting the tokens

tokens.sort()

Sorting arranges the tokens in non-decreasing order, which enables the algorithm to always pick the smallest token for a face-up move and the largest token for a face-down move. This ordering is essential for the greedy strategy that follows.

Initializing pointers and state variables

result = 0
score = 0
left  = 0
right = len(tokens) - 1

left points to the smallest unused token, right points to the largest unused token. score tracks the current score, and result records the best score seen so far.

Main processing loop

while left <= right:
    ...

The loop continues while there remain unprocessed tokens between the two pointers. Inside the loop the algorithm decides whether a face-up or a face-down move is possible.

Face-up move (use smallest token)

if tokens[left] <= power:
    power -= tokens[left]
    left  += 1
    score += 1
    result = max(result, score)
    continue

When the current power is sufficient to cover the smallest token, the algorithm spends that power, advances the left pointer, increments the score, and updates result. The continue statement restarts the loop to re-evaluate the new state.

Face-down move (recover power using largest token)

if score > 0:
    power += tokens[right]
    right -= 1
    score -= 1
    continue

If a face-up move is not possible but the score is positive, the algorithm trades one point of score for the power value of the largest remaining token. The right pointer moves inward, and the score is decremented. The loop then iterates again.

Termination condition

break  # no token possible

When neither a face-up nor a face-down move can be performed-i.e., the smallest token exceeds the available power and the score is zero-the loop exits, and the method returns the best score recorded.

Edge Cases Handled

When the input list tokens is empty, right becomes -1, causing the loop condition left <= right to be false immediately; the method returns 0, which correctly reflects that no moves are possible.

If every token value exceeds the initial power, the first if condition fails, and because score starts at 0, the second condition also fails, leading to an immediate break and a result of 0.

When the algorithm gains power through a face-down move, it may enable subsequent face-up moves that were previously impossible; the loop’s structure naturally re-evaluates the state after each operation, ensuring that newly affordable tokens are considered.

If the score drops to 0 after a series of face-down moves, the algorithm will no longer attempt further face-down moves, preventing an infinite loop and correctly terminating when no further progress can be made.

Performance Optimizations

The algorithm performs a single sort, which orders the tokens once and avoids repeated searches for minimum or maximum values during the main loop. By using two indices (left and right) that move inward, each token is examined at most once, eliminating the need for additional data structures or repeated scanning.

The result = max(result, score) update occurs only after a successful face-up move, avoiding unnecessary comparisons when the score does not change.

The early break when no operation is possible prevents needless iterations once the reachable state space is exhausted, ensuring that the loop runs only while progress can be made.

Overall, the combination of sorting, two-pointer traversal, and early termination yields an efficient execution path that scales well with the size of the input token list.

written by openai gpt

ELI5 - Simplified Explanation

Imagine a game where a bag contains many numbered tokens and a pile of power points. The goal is to collect as many points as possible by playing these tokens. First, all the tokens are lined up from the smallest number to the largest. A marker starts at the beginning of the line and another marker starts at the end of the line.

When the power is high enough to cover the number on the smallest token, that token is played face-up. This uses up some power, adds a point to the score, and moves the marker forward to the next small token. Whenever a point is gained, the best record of points is updated.

If there is not enough power to play a small token but at least one point has already been earned, a different move becomes possible. The largest token in the line is played face-down. This gives back some power, moves the marker backward to the next large token, and takes away one point.

These moves keep happening until it is no longer possible to play a small token for a point or trade a point for more power. Once the loop stops, the game is finished.

written by google gemini

Code Quality

Several LLMs ranked my code quality on a scale from 1 (very poor) to 10 (outstanding):
n = 26 | median = 8 | μ = 8.19 | σ = 0.79

Complexity Analysis

Time: loglinear
As a rule of thumb, the maximum input size for one second execution time is
  • factorial: up to 10 elements
  • exponential: up to 20 elements
  • polynomial: a few thousand elements
  • loglinear: up to 100,000 elements
  • linear: a few million elements
  • logarithmic: a billion elements
  • constant: practically unlimited
generated automatically

Other Solutions

I wrote a basic crawler to find other solutions to that problem.
Obviously, I did that after I solved the problem myself.

In general, AlgoMonster and WalkCCC solutions are high-quality and always worth a look.
I haven't checked most of the other solutions, but they might be helpful as well.

And of course, the LeetCode forum is always a good place (or even the best) to look for alternative approaches.

(click on a column header to sort the table)
author
author solutions
www AlgoMonster C++ Python Java TS
WalkCCC C++ Python Java
leetcode.ca C++ Python Java Go TS
LeetcodeHelp C++ Python Java
Progiez C++ Python Java
github black-shadows C++
charles-wangkai Java
everthis JS
fsq C++
JoshCrozier JS
lkwq007 Python
pruthvikp Python
suxrobGM C#
trung-hn Python
varunu28 Java
vthwang Java
wisdompeak C++
AlgoMonster C++, Python, Java, TypeScript
WalkCCC C++, Python, Java
leetcode.ca C++, Go, Java, Python, TypeScript
LeetcodeHelp C++, Java, Python
Progiez C++, Java, Python
black-shadows C++, C++
charles-wangkai Java
everthis JavaScript
fsq C++
JoshCrozier JavaScript
lkwq007 Python
pruthvikp Python
suxrobGM C#
trung-hn Python
varunu28 Java
vthwang Java
wisdompeak C++
30 links | 17 authors | 7 languages

Videos

5 videos   did my crawler come up with invalid videos ? drop me a line.

Solved On The Same Day

1 medium 1 hard
3 solutions   February 28, 2024

Extra

There are a few extra pages giving you some insights into my setup:
  • Tech Stack - my development environment and tools
  • AI - how AI helped me create this website (NOT solving the problems)
  • Progress - progression over time
  • Quality - code quality