Input: tokens =[100], power =50Output: 0Explanation: Playing the only token in the bag is impossible because you either have too little power or too little score.
Example 2:
1
2
3
4
Input: tokens =[100,200], power =150Output: 1Explanation: 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:
1
2
3
4
5
6
7
Input: tokens =[100,200,300,400], power =200Output: 2Explanation: Play the tokens inthis 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.
The key idea is to maximize score by always playing the smallest token face up when possible (to gain score cheaply), and if stuck, play the largest token face down (to regain power by sacrificing score). This greedy approach ensures we use our resources optimally.
classSolution:
defbagOfTokensScore(self, tokens: list[int], power: int) -> int:
tokens.sort()
l, r =0, len(tokens) -1 ans = score =0 p = power
while l <= r:
if p >= tokens[l]:
p -= tokens[l]
score +=1 l +=1 ans = max(ans, score)
elif score >0:
p += tokens[r]
score -=1 r -=1else:
breakreturn ans
classSolution {
funbagOfTokensScore(tokens: IntArray, power: Int): Int {
tokens.sort()
var l = 0var r = tokens.size - 1var ans = 0var score = 0var p = power
while (l <= r) {
if (p >= tokens[l]) {
p -= tokens[l++]
score++ ans = maxOf(ans, score)
} elseif (score > 0) {
p += tokens[r--]
score-- } else {
break }
}
return ans
}
}
impl Solution {
pubfnbag_of_tokens_score(mut tokens: Vec<i32>, power: i32) -> i32 {
tokens.sort();
let (mut l, mut r) = (0, tokens.len().wrapping_sub(1));
let (mut ans, mut score, mut p) = (0, 0, power);
while l <= r {
if p >= tokens[l] {
p -= tokens[l];
score +=1;
l +=1;
ans = ans.max(score);
} elseif score >0 {
p += tokens[r];
score -=1;
if r ==0 { break; }
r -=1;
} else {
break;
}
}
ans
}
}