Leetcode 985 Solution

This article provides solution to leetcode question 985 (bag-of-tokens)

https://leetcode.com/problems/bag-of-tokens

Solution

class Solution:
    def bagOfTokensScore(self, tokens: List[int], P: int) -> int:
        tokens.sort()

        if not tokens or P < tokens[0]:
            return 0

        l = 0
        r = len(tokens) - 1

        left = sum(tokens)
        while l < r:
            if P >= left:
                return r - l + 1
            elif P >= left - tokens[r]:
                return r - l

            P = P - tokens[l] + tokens[r]
            left -= tokens[l] + tokens[r]
            l += 1
            r -= 1

        return 1 if l == r and P > tokens[l] else 0