Off-by-one on range boundaries
Wrong move: Loop endpoints miss first/last candidate.
Usually fails on: Fails on minimal arrays and exact-boundary answers.
Fix: Re-derive loops from inclusive/exclusive ranges before coding.
Move from brute-force thinking to an efficient approach using array strategy.
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. In one move, you can play an unplayed token in one of the two ways (but not both for the same token):
tokens[i], you may play tokeni, losing tokens[i] power and gaining 1 score.1, you may play tokeni, gaining tokens[i] power and losing 1 score.Return the maximum possible score you can achieve after playing any number of tokens.
Example 1:
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).
Example 2:
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.
There is no need to play token0, since you cannot play it face-up to add to your score. The maximum score achievable is 1.
Example 3:
Input: tokens = [100,200,300,400], power = 200
Output: 2
Explanation: Play the tokens in this order to get a score of 2:
100) face-up, reducing power to 100 and increasing score to 1.400) face-down, increasing power to 500 and reducing score to 0.200) face-up, reducing power to 300 and increasing score to 1.300) face-up, reducing power to 0 and increasing score to 2.The maximum score achievable is 2.
Constraints:
0 <= tokens.length <= 10000 <= tokens[i], power < 104Problem summary: 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. In one move, you can play an unplayed token in one of the two ways (but not both for the same token): Face-up: If your current power is at least tokens[i], you may play tokeni, losing tokens[i] power and gaining 1 score. Face-down: If your current score is at least 1, you may play tokeni, gaining tokens[i] power and losing 1 score. Return the maximum possible score you can achieve after playing any number of tokens.
Start with the most direct exhaustive search. That gives a correctness anchor before optimizing.
Pattern signal: Array · Two Pointers · Greedy
[100] 50
[200,100] 150
[100,200,300,400] 200
Source-backed implementations are provided below for direct study and interview prep.
// Accepted solution for LeetCode #948: Bag of Tokens
class Solution {
public int bagOfTokensScore(int[] tokens, int power) {
Arrays.sort(tokens);
int ans = 0, score = 0;
for (int i = 0, j = tokens.length - 1; i <= j;) {
if (power >= tokens[i]) {
power -= tokens[i++];
ans = Math.max(ans, ++score);
} else if (score > 0) {
power += tokens[j--];
--score;
} else {
break;
}
}
return ans;
}
}
// Accepted solution for LeetCode #948: Bag of Tokens
func bagOfTokensScore(tokens []int, power int) (ans int) {
sort.Ints(tokens)
i, j := 0, len(tokens)-1
score := 0
for i <= j {
if power >= tokens[i] {
power -= tokens[i]
i++
score++
ans = max(ans, score)
} else if score > 0 {
power += tokens[j]
j--
score--
} else {
break
}
}
return
}
# Accepted solution for LeetCode #948: Bag of Tokens
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
// Accepted solution for LeetCode #948: Bag of Tokens
struct Solution;
impl Solution {
fn bag_of_tokens_score(mut tokens: Vec<i32>, mut p: i32) -> i32 {
let n = tokens.len();
if n == 0 {
return 0;
}
tokens.sort_unstable();
let mut l = 0;
let mut r = n - 1;
let mut point = 0;
let mut res = 0;
while l <= r {
if tokens[l] <= p {
p -= tokens[l];
point += 1;
res = res.max(point);
l += 1;
} else {
if point > 0 {
p += tokens[r];
point -= 1;
r -= 1;
} else {
break;
}
}
}
res
}
}
#[test]
fn test() {
let tokens = vec![100];
let p = 50;
let res = 0;
assert_eq!(Solution::bag_of_tokens_score(tokens, p), res);
let tokens = vec![100, 200];
let p = 150;
let res = 1;
assert_eq!(Solution::bag_of_tokens_score(tokens, p), res);
let tokens = vec![100, 200, 300, 400];
let p = 200;
let res = 2;
assert_eq!(Solution::bag_of_tokens_score(tokens, p), res);
}
// Accepted solution for LeetCode #948: Bag of Tokens
function bagOfTokensScore(tokens: number[], power: number): number {
tokens.sort((a, b) => a - b);
let [i, j] = [0, tokens.length - 1];
let [ans, score] = [0, 0];
while (i <= j) {
if (power >= tokens[i]) {
power -= tokens[i++];
ans = Math.max(ans, ++score);
} else if (score) {
power += tokens[j--];
score--;
} else {
break;
}
}
return ans;
}
Use this to step through a reusable interview workflow for this problem.
Two nested loops check every pair of elements. The outer loop picks one element, the inner loop scans the rest. For n elements that is n × (n−1)/2 comparisons = O(n²). No extra memory — just two loop variables.
Each pointer traverses the array at most once. With two pointers moving inward (or both moving right), the total number of steps is bounded by n. Each comparison is O(1), giving O(n) overall. No auxiliary data structures are needed — just two index variables.
Review these before coding to avoid predictable interview regressions.
Wrong move: Loop endpoints miss first/last candidate.
Usually fails on: Fails on minimal arrays and exact-boundary answers.
Fix: Re-derive loops from inclusive/exclusive ranges before coding.
Wrong move: Advancing both pointers shrinks the search space too aggressively and skips candidates.
Usually fails on: A valid pair can be skipped when only one side should move.
Fix: Move exactly one pointer per decision branch based on invariant.
Wrong move: Locally optimal choices may fail globally.
Usually fails on: Counterexamples appear on crafted input orderings.
Fix: Verify with exchange argument or monotonic objective before committing.