Posted on

Description

Submission

class Solution {
public:
    int bagOfTokensScore(vector<int>& tokens, int P) {
        if(tokens.empty()) return 0;
        int n = tokens.size();
        
        sort(tokens.begin(), tokens.end());

        int score = 0, ret = 0;

        for(int i = 0, j = n - 1; i <= j;) {
            if(tokens[i] <= P) {
                score++;
                P -= tokens[i++];
                ret = max(ret, score);
            } else if(score > 0) {
                P += tokens[j--];
                score--;
            } else {
                break;
            }
        }   

        return ret;
    }
};

Leave a Reply

Your email address will not be published. Required fields are marked *