-
Notifications
You must be signed in to change notification settings - Fork 0
/
BagofTokens.java
49 lines (44 loc) · 1.13 KB
/
BagofTokens.java
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
41
42
43
44
45
46
47
48
49
package greedy;
import java.util.Arrays;
public class BagofTokens {
public int bagOfTokensScore(int[] tokens, int P) {
int score=0;
Arrays.sort(tokens);
int low=0;
int n=tokens.length-1;
for(int i=0;i<=n;i++){
if(P>=tokens[i]){
score++;
P-=tokens[i];
}else if (i!=n && P<tokens[i] && tokens[n]>P && score>0) {
P+=tokens[n];
score--;
n--;i--;
}else {
break;
}
}
// System.out.println(P);
return score;
}
public int bagOfTokensScoreOptimized(int[] tokens, int P) {
Arrays.sort(tokens);
int result=0;
int S=0;
for (int i=0,j=tokens.length-1;i<=j;) {
if (P>=tokens[i]) {
S++;
P-=tokens[i++];
result=Math.max(S, result);
continue;
}
if (S>0) {
S--;
P+=tokens[j--];
} else {
break;
}
}
return result;
}
}