You have an initial power
P , an initial score of
0 points, and a bag of tokens.
Each token can be used at most once, has a value
token[i] , and has potentially two ways to use it.
- If we have at least
token[i]power, we may play the token face up, losing
token[i]power, and gaining
- If we have at least
1point, we may play the token face down, gaining
token[i]power, and losing
Return the largest number of points we can have after playing any number of tokens.
If we play a token face up, we might as well play the one with the smallest value. Similarly, if we play a token face down, we might as well play the one with the largest value.
We don’t need to play anything until absolutely necessary. Let’s play tokens face up until we can’t, then play a token face down and continue.
We must be careful, as it is easy for our implementation to be incorrect if we do not handle corner cases correctly. We should always play tokens face up until exhaustion, then play one token face down and continue.
Our loop must be constructed with the right termination condition: we can either play a token face up or face down.
Our final answer could be any of the intermediate answers we got after playing tokens face up (but before playing them face down.)
def bagOfTokensScore(tokens, P): tokens.sort() tokensLeft = len(tokens) points = 0 def findTokenToPoints(): for i in range(len(tokens)): if tokens[i] != -1 and tokens[i] <= P: return i return -1 while True: #With the given power, can you get any points? i = findTokenToPoints() if tokensLeft == 0: return points if i == -1: #No #Can you gain some power with points if points != 0: #Following snippet is to exchange points for power maxIndex = -1 for i in range(len(tokens)-1, -1, -1): if tokens[i] != -1: maxIndex = i break if maxIndex == -1 or tokensLeft==1: return points points -= 1 P += tokens[maxIndex] tokens[maxIndex] = -1 tokensLeft -= 1 else: return 0 else: #Yes #exhange power for points points += 1 P -= tokens[i] tokens[i] = -1 tokensLeft -= 1
def bagOfTokensScore(tokens, P): tokens.sort() deque = collections.deque(tokens) ans = bns = 0 while deque and (P >= deque or bns): while deque and P >= deque: P -= deque.popleft() bns += 1 ans = max(ans, bns) if deque and bns: P += deque.pop() bns -= 1 return ans
O(N log N), where N is the length of tokens.