Skip to content

Instantly share code, notes, and snippets.

@SuryaPratapK
Created March 11, 2024 15:04
Show Gist options
  • Save SuryaPratapK/2bcb866c4d0dd5042addcce7cc9451fc to your computer and use it in GitHub Desktop.
Save SuryaPratapK/2bcb866c4d0dd5042addcce7cc9451fc to your computer and use it in GitHub Desktop.
class Solution {
public:
int bagOfTokensScore(vector<int>& tokens, int power) {
int n = tokens.size();
sort(tokens.begin(),tokens.end());//sort to make choice-maing obvious
//2-pointer approach
int left=0,right=n-1;
int score = 0,ans = 0;
while(left<=right){
while(left<=right and tokens[left]<=power){//greedily score in increasing order of token value
power-=tokens[left];
left++;
score++;
}
ans = score;//update new higher score
if(left<=right and score>0){//get a score from right
power+=tokens[right];
right--;
score--;
} else {//not possible to get any more score
break;
}
}
return ans;
}
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment