# LeetCode: 948. 令牌放置¶

## 1、题目描述¶

输入：tokens = [100], P = 50



输入：tokens = [100,200], P = 150



输入：tokens = [100,200,300,400], P = 200



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

## 2、解题思路¶

• 排序+双指针

• 需要注意的就是，不能直接将牌子反过来导致分数为负

class Solution:
def bagOfTokensScore(self, tokens: List[int], P: int) -> int:
score = 0
power = P
sums = 0
tokens.sort()
length = len(tokens)

left, right = 0, length - 1

while left < right:
if power >= sums + tokens[left]:
score += 1
sums += tokens[left]
else:
if score:
sums += tokens[left]
power += tokens[right]
right -= 1

else:
break
left += 1
if left == right and sums + tokens[left] <= power:
score += 1
return score


• 首先判断能量是否足够翻第一张牌，不够的话，直接返回0
• 然后左右指针逼近即可
class Solution:
def bagOfTokensScore(self, tokens: List[int], P: int) -> int:
score = 0
power = P
sums = 0
tokens.sort()
length = len(tokens)
if not tokens or power < tokens[0]:
return score
left, right = 0, length - 1

while left < right:
sums += tokens[left]
if power < sums:
power += tokens[right]
right -= 1
score -= 1
score += 1
left += 1

if left == right and sums + tokens[left] <= power:
score += 1
return score