-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathBagOfTokens.java
More file actions
40 lines (32 loc) · 919 Bytes
/
BagOfTokens.java
File metadata and controls
40 lines (32 loc) · 919 Bytes
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
import java.util.*;
class Solution {
public int bagOfTokensScore(int[] tokens, int power) {
if(tokens == null || tokens.length == 0) return 0;
Arrays.sort(tokens);
if(power < tokens[0]) return 0;
int start=0, end=tokens.length-1;
int score=0;
while(start <= end){
if(power >= tokens[start]){
power -= tokens[start];
start++;
score++;
}
else if(score >= 1 && start < end){
power += tokens[end];
end--;
score--;
}
else break;
}
return score;
}
}
class BagOfTokens{
public static void main(String[] args) {
Solution obj= new Solution();
int nums[]={100,200,300,400};
int power=200;
System.out.println(obj.bagOfTokensScore(nums, power));
}
}