competitive-programmingSep 12, 20221 min read
[Leetcode] 948. Bag of Tokens explained
Updated: Sep 12, 2022
SortingsTwo pointers
Available in:enko
#Problem
#Approach
Sort the tokens array in ascending order.
Keep left and right indices, which denotes allowed tokens available with initialPower.
left 0
right n-1
While left <= right:
- Find maximum
scorewe can make with tokens in[left, right]and updatemaximumScore. - Subtract
tokens[l]frominitialPowerand addtokens[r]toinitialPower. - Increment
leftby 1, and decrementrightby 1.
Return maxScore value in the end.
Sorting apparently takes .
The indices left and right covers all n tokens, and each time there is a computation with n-complexity.
Thie makes time complexity .
#Code

class Solution {
public int bagOfTokensScore(int[] tokens, int initialPower) {
Arrays.sort(tokens);
int n= tokens.length, l= 0, r= n-1;
int maxScore= 0;
while (l <= r) {
if (tokens[l] > initialPower) break;
int idx= l, score= 0, power= initialPower;
while (idx <= r && tokens[idx] <= power) {
power -= tokens[idx++];
++score;
}
maxScore= Math.max(maxScore, score);
initialPower += (tokens[r]-tokens[l]);
++l; --r;
}
return maxScore;
}
}
#Complexity
- Time:
- Space: