classSolution{public:intbagOfTokensScore(vector<int>&tokens,intpower){intans=0;intscore=0;inti=0;// Index of smallest tokenintj=tokens.size()-1;// Index of largest tokensort(begin(tokens),end(tokens));while(i<=j&&(power>=tokens[i]||score)){while(i<=j&&power>=tokens[i]){// Play the smallest face uppower-=tokens[i++];++score;}ans=max(ans,score);if(i<=j&&score){// Play the largest face downpower+=tokens[j--];--score;}}returnans;}};
classSolution{publicintbagOfTokensScore(int[]tokens,intpower){intans=0;intscore=0;inti=0;// Index of smallest tokenintj=tokens.length-1;// Index of largest tokenArrays.sort(tokens);while(i<=j&&(power>=tokens[i]||score>0)){while(i<=j&&power>=tokens[i]){// Play the smallest face uppower-=tokens[i++];++score;}ans=Math.max(ans,score);if(i<=j&&score>0){// Play the largest face downpower+=tokens[j--];--score;}}returnans;}}
classSolution:defbagOfTokensScore(self,tokens:List[int],power:int)->int:ans=0score=0q=deque(sorted(tokens))whileqand(power>=q[0]orscore):whileqandpower>=q[0]:# Play the smallest face uppower-=q.popleft()score+=1ans=max(ans,score)ifqandscore:# Play the largest face downpower+=q.pop()score-=1returnans