lc948. Bag of Tokens

  1. Bag of Tokens Medium

96python

83數組

Favoritebash

Share You have an initial power P, an initial score of 0 points, and a bag of tokens.ui

Each token can be used at most once, has a value token[i], and has potentially two ways to use it.spa

If we have at least token[i] power, we may play the token face up, losing token[i] power, and gaining 1 point. If we have at least 1 point, we may play the token face down, gaining token[i] power, and losing 1 point. Return the largest number of points we can have after playing any number of tokens.code

Example 1:排序

Input: tokens = [100], P = 50 Output: 0 Example 2:token

Input: tokens = [100,200], P = 150 Output: 1 Example 3:it

Input: tokens = [100,200,300,400], P = 200 Output: 2io

Note:

tokens.length <= 1000 0 <= tokens[i] < 10000 0 <= P < 10000

思路:先對數組排序,而後按照題目要求計算,得出結論

代碼:python3

class Solution:
    def bagOfTokensScore(self, tokens: List[int], P: int) -> int:
        tokens.sort()
        l,r,score=0,len(tokens)-1,0
        while l<=r:
            if tokens[l]<=P:
                P=P-tokens[l]
                score+=1
                l+=1
            elif score and l!=r:
                P=P+tokens[r]
                score-=1
                r-=1
            else:
                break
        return score

複製代碼
相關文章
相關標籤/搜索