101 Logo
onenoughtone

Problem Statement

Token Strategy Game

You're playing a strategic card game where you need to manage your power and score to maximize your points.

You have an initial power value, an initial score of 0, and a bag of tokens where each token has a specific value.

Each token can be used at most once, and you can play it in one of two ways:

  • If your current power is at least equal to the token's value, you may play the token face up, losing that much power but gaining 1 score.
  • If your current score is at least 1, you may play the token face down, gaining that much power but losing 1 score.

You can play the tokens in any order, and you don't have to play all of them.

Return the maximum score you can achieve after playing any number of tokens.

Examples

Example 1:

Input: tokens = [100], power = 50
Output: 0
Explanation: Playing the only token in the bag is impossible because you have too little power and no score to play it either way.

Example 2:

Input: tokens = [100,200], power = 150
Output: 1
Explanation: Play the 0th token (100) face up, your power becomes 50 and score becomes 1. There is no need to play the 1st token since you cannot play it face up to add to your score.

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: 1. Play the 0th token (100) face up, your power becomes 100 and score becomes 1. 2. Play the 3rd token (400) face down, your power becomes 500 and score becomes 0. 3. Play the 1st token (200) face up, your power becomes 300 and score becomes 1. 4. Play the 2nd token (300) face up, your power becomes 0 and score becomes 2.

Constraints

  • 0 <= tokens.length <= 1000
  • 0 <= tokens[i], power < 10^4

Problem Breakdown

To solve this problem, we need to:

  1. Sorting the tokens is key to developing an optimal strategy
  2. Playing tokens with small values face up and tokens with large values face down is generally beneficial
  3. You need to balance gaining power and gaining score throughout the game
  4. The greedy approach works well for this problem because you can always make the locally optimal choice
  5. You might need to temporarily decrease your score to gain more power, which can lead to a higher final score
  6. Not all tokens need to be played to achieve the maximum score
ProblemSolutionCode
101 Logo
onenoughtone