class Solution:
def bagOfTokensScore(self, tokens: List[int], P: int) -> int:
# time O(NlgN) space O(N)
# main idea: sort , then buy at the cheapest and sell at the most expensive using queue
tokens.sort()
q = collections.deque(tokens)
cur = 0
res = 0
# continue condition: when there is non-zero current score or there is enough buying power
while q and (q[0] <= P or cur):
if q[0] <= P :
P -= q.popleft()
cur += 1
else:
P += q.pop()
cur -= 1
res = max(cur,res)
return res