[LeetCode] Bag of Tokens

948. Bag of Tokens

You have an initial power of power, 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 the ith token face up, losing tokens[i] power and gaining 1 score.
  • If your current score is at least 1, you may play the ith token face down, gaining tokens[i] power and losing 1 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.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
class Solution {
public:
int bagOfTokensScore(vector<int>& A, int power) {
sort(begin(A), end(A));
vector<int> psum{0};
int res = 0, n = A.size(), l = 0, r = n - 1;
for(int i = 0; i < n; i++)
psum.push_back(psum.back() + A[i]);
while(l <= r) {
if(psum[r + 1] - psum[l] <= power) {
return max(res, r - l + 1);
}
if(psum[r] - psum[l] <= power) {
return max(res, r - l);
}
if(A[l] > power) break;
power += A[r--] - A[l++];
}

if(l <= r and psum[r + 1] - psum[l] <= power)
res = max(res, r - l + 1);
return res;
}
};
Author: Song Hayoung
Link: https://songhayoung.github.io/2022/06/01/PS/LeetCode/bag-of-tokens/
Copyright Notice: All articles in this blog are licensed under CC BY-NC-SA 4.0 unless stating additionally.