-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathBag_of_tokens.java
47 lines (47 loc) · 1.28 KB
/
Bag_of_tokens.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
class Solution {
public int bagOfTokensScore(int[] tokens, int power) {
int score = 0,last=tokens.length,ans=0,i=0;
quicksort(tokens,0,last-1);
while(i<last && (power >= tokens[i] || score > 0)){
if(power >= tokens[i]){
power -= tokens[i];
score++;
i++;
}
else{
score--;
power += tokens[--last];
}
ans = Math.max(score,ans);
}
return ans;
}
private void quicksort(int[] arr, int left, int right)
{
if (left < right)
{
int pivotIndex = partition(arr, left, right);
quicksort(arr, left, pivotIndex - 1);
quicksort(arr, pivotIndex + 1, right);
}
}
private int partition(int[] arr, int left, int right)
{
int pivotValue = arr[right];
int i = left - 1;
for (int j = left; j < right; j++)
{
if (arr[j] < pivotValue)
{
i++;
int temp = arr[i];
arr[i] = arr[j];
arr[j] = temp;
}
}
int temp = arr[i + 1];
arr[i + 1] = arr[right];
arr[right] = temp;
return i + 1;
}
}