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, losingtoken[i]
power, and gaining1
point. - If we have at least
1
point, we may play the token face down, gainingtoken[i]
power, and losing1
point.
Return the largest number of points we can have after playing any number of tokens.
Example 1:
Input: tokens = [100], P = 50 Output: 0
Example 2:
Input: tokens = [100,200], P = 150 Output: 1
Example 3:
Input: tokens = [100,200,300,400], P = 200 Output: 2
Note:
tokens.length <= 1000
0 <= tokens[i] < 10000
0 <= P < 10000
题目理解:
给定初始体力,可以消耗体力得到token,也可以消耗token得到体力,每一个token对应不同的体力,体力和token数都不能为负。问最多能得到多少token
解题思路:
将token按照排序,从最左开始,最可能多的买token,不能买的时候,用token换最右一个token的体力,直到遍历所有token或者无法买token也无法换体力
代码如下:
class Solution {
public int bagOfTokensScore(int[] tokens, int P) {
Arrays.sort(tokens);
int res = 0, local = 0;
for(int left = 0, right = tokens.length - 1; left <= right; left++){
if(P >= tokens[left]){
local++;
P -= tokens[left];
res = Math.max(res, local);
}
else{
if(local == 0)
break;
local--;
P += tokens[right--];
left--;
}
}
return res;
}
}