Bag of Tokens LeetCode solution in Java

1
class Solution {
2
public int bagOfTokensScore(int[] tokens, int power) {
3
// initially score is 0, that's why in these conditions, return 0.
4
if (tokens.length == 0 || power < tokens[0]) return 0;
5
Arrays.sort(tokens); // sort the array
6

7
int i = 0;
8
int r = tokens.length - 1;
9
int score = 0;
10
int answer = 0;
11

12
while (i <= r) {
13
if (power >= tokens[i]) {
14
power -= tokens[i++];
15
answer = Math.max(answer, ++score); // play all tokens, but store the max score in answer.
16
} else if (score > 0) {
17
power += tokens[r--]; // take power from greatest element
18
score--; // decrease by 1.
19
}
20
// when you can't do any of the steps (face up, face down)
21
else return answer;
22
}
23
return answer;
24
}
25
}

0

WPM •0 •0

100%

ACC •0 •0

0s

TIME •0