You are given 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 token*i*.
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 token*i*, losing tokens[i]
power and gaining 1
score.1
, you may play token*i*, gaining tokens[i]
power and losing 1
score.Return the maximum possible score you can achieve after playing any number of tokens.
Example 1:
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:
tokens = [200,100], power = 150
Output: 1
Explanation: Play token*1* (100
) face-up, reducing your power to 50
and increasing your score to 1
.
There is no need to play token*0*, since you cannot play it face-up to add to your score. The maximum score achievable is 1
.
Example 3:
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
.Constraints:
0 <= tokens.length <= 1000
0 <= tokens[i], power < 10^4
A brute-force approach would involve exploring all possible combinations of playing tokens face-up or face-down and keeping track of the maximum score achieved. This can be done using recursion. However, this approach is not efficient.
To maximize the score, we should use a greedy approach. Sort the tokens in ascending order. Then, try to play the smallest tokens face-up to gain score. If the power is not enough to play the smallest token face-up, and if we have a score greater than 0, then play the largest token face-down to gain power. This way, we can maximize our score.
power
, score
, left
(0), and right
(tokens.length - 1).left <= right
:
power >= tokens[left]
, play the token face-up:
power -= tokens[left]
score += 1
left += 1
maxScore = max(maxScore, score)
score > 0
:
power += tokens[right]
score -= 1
right -= 1
maxScore
import java.util.Arrays;
class Solution {
public int bagOfTokensScore(int[] tokens, int power) {
Arrays.sort(tokens);
int score = 0;
int maxScore = 0;
int left = 0;
int right = tokens.length - 1;
while (left <= right) {
if (power >= tokens[left]) {
power -= tokens[left];
score++;
left++;
maxScore = Math.max(maxScore, score);
} else if (score > 0) {
power += tokens[right];
score--;
right--;
} else {
break;
}
}
return maxScore;
}
}
tokens
array: return 0.power
is less than the smallest token and initial score
is 0: return 0.tokens.length
.