948. Bag of Tokens
Description
You have an initial power of P
, an initial score of 0
, and a bag of tokens
where tokens[i]
is the value of the ith
token (0-indexed).
Your goal is to maximize your total score by potentially playing each token in one of two ways:
If your current power is at least
tokens[i]
, you may play theith
token face up, losingtokens[i]
power and gaining1
score.If your current score is at least
1
, you may play theith
token face down, gainingtokens[i]
power and losing1
score.
Each token may be played at most once and in any order. You do not have to play all the tokens.
Return the largest possible score you can achieve after playing any number of tokens.
Constraints
0 <= tokens.length <= 1000
0 <= tokens[i], P < 104
Approach
Links
GeeksforGeeks
ProgramCreek
Examples
Input: tokens = [100], P = 50
Output: 0
Explanation: Playing the only token in the bag is impossible because you either have too little power or too little score.
Solutions
/**
* Time complexity :
* Space complexity :
*/
class Solution {
public int bagOfTokensScore(int[] tokens, int P) {
if(tokens == null) return 0;
Arrays.sort(tokens);
int left = 0, right = tokens.length-1;
int score = 0;
while(left <= right) {
if(tokens[left] <= P) {
P -= tokens[left++];
score++;
} else {
if(left < right && score > 0 &&
tokens[left] <= (tokens[right]+P)) {
P += tokens[right--];
score--;
} else {
break;
}
}
}
return score;
}
}
Follow up
Last updated
Was this helpful?