948. Bag of Tokens

本文介绍了一种使用two-pointer算法解决的代币游戏问题,玩家通过消耗或获取能量来使用代币,目标是最大化得分。文章提供了详细的算法实现,并通过实例展示了如何在不同条件下获得最大分数。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

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 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.

 

Example 1:

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

Example 2:

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

Example 3:

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

 

Note:

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

思路:典型的two-pointer

class Solution(object):
    def bagOfTokensScore(self, tokens, P):
        """
        :type tokens: List[int]
        :type P: int
        :rtype: int
        """
        if not tokens: return 0
        tokens.sort()
        if P<tokens[0]: return 0
        i,j=0,len(tokens)-1
        res=points=0
        while i<=j:
            while i<=j and P>=tokens[i]:
                points+=1
                P-=tokens[i]
                res=max(res,points)
                i+=1
            points-=1
            P+=tokens[j]
            j-=1
        return res
    
s=Solution()
print(s.bagOfTokensScore(tokens = [81,91,31], P = 73))
print(s.bagOfTokensScore(tokens = [26], P = 50))
print(s.bagOfTokensScore(tokens = [100], P = 50))
print(s.bagOfTokensScore(tokens = [100,200], P = 150))
print(s.bagOfTokensScore(tokens = [100,200,300,400], P = 200))

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值