Bag of Tokens

Problem Id: 948 Difficulty: Medium


Intuition

Solution


class Solution:
    def bagOfTokensScore(self, tokens: List[int], P: int) -> int:
        if not tokens:
            return 0

        tokens.sort()
        lo = 0
        hi = len(tokens) - 1
        score = 0
        while True:
            if hi >= lo and P >= tokens[lo]:
                P -= tokens[lo]
                lo += 1
                score += 1
            elif score > 0 and hi > lo:
                P += tokens[hi]
                hi -= 1
                score -= 1
            else:
                break
        return score