Created
March 11, 2024 15:04
-
-
Save SuryaPratapK/2bcb866c4d0dd5042addcce7cc9451fc to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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