Skip to main content
Back to problems
#948
Medium Algorithms

Bag of tokens

Array Two Pointers Greedy Sorting
59.5% acceptance
Feb 25, 2026
3459
547
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.

Solution

Rust
Time O(n log n)
Space O(1)
LeetCode
solution.rs
impl Solution {
  pub fn bag_of_tokens_score(tokens: Vec<i32>, power: i32) -> i32 {
    let mut tokens = tokens;
    tokens.sort();
    let mut lo = 0;
    let mut hi = tokens.len() as i32 - 1;
    let mut power = power;
    let mut score = 0i32;
    let mut max_score = 0i32;
    while lo <= hi {
      if power >= tokens[lo as usize] {
        power -= tokens[lo as usize];
        score += 1;
        max_score = max_score.max(score);
        lo += 1;
      } else if score > 0 {
        power += tokens[hi as usize];
        score -= 1;
        hi -= 1;
      } else {
        break;
      }
    }
    max_score
  }
}