一、题目描述
You have an initial power P, an initial score of 0 points, and a bag of tokens.
Each token can be used at most once, has a value token[i], and has potentially two ways to use it.
- If we have at least token[i] power, we may play the token face up, losing token[i] power, and gaining 1 point.
- If we have at least 1 point, we may play the token face down, gaining token[i] power, and losing 1 point.
Return the largest number of points we can have after playing any number of tokens.
Input: tokens = [100,200,300,400], P = 200
Output: 2
二、题解
方法一:排序 + 策略
编码错误,思想正确:
- 这里有 2 个点需要注意:
P < tokens[l]
而且P <= 0
时,即连具有最少能量的令牌都不能翻反来获取能量的情况下,游戏是需要结束的。- 在使用任意数量的令牌后,返回我们可以得到的最大分数,即不需要全都使用把令牌一遍,所以需要记录翻的时候的
score
的最大值。
public int bagOfTokensScore(int[] tokens, int P) {
Arrays.sort(tokens);
int score = 0;
int l = 0, r = tokens.length-1;
while (l <= r) {
if (P >= tokens[l]) {
P -= tokens[l++];
score++;
} else {
P += tokens[r--];
score--;
}
}
return score;
}
- 如果我有足够的能量,我肯定是先把能量小的翻正,尽量拿分
score++
。 - 否则,将能量最大的令牌翻转,因为这样会失去一分,但我也要拿到足够多的能量,为下次的得分做铺垫。
public int bagOfTokensScore(int[] tokens, int P) {
Arrays.sort(tokens);
int score = 0, max = 0;
int l = 0, r = tokens.length-1;
while (l <= r) {
if (P >= tokens[l]) {
P -= tokens[l++];
score++;
} else {
if (score == 0) {
return max;
}
P += tokens[r--];
score--;
}
max = Math.max(max, score);
}
return max;
}
复杂度分析
- 时间复杂度: ,
- 空间复杂度: ,