zoukankan      html  css  js  c++  java
  • 【leetcode】948. Bag of Tokens

    题目如下:

    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

    解题思路:本题可以用贪心算法。即可以得分的时候优先选择当前最小的token[i]得分,不能得分的时候选择当前可选的最大的token[i]换取power。所以只需要将tokens排序,分别从两端选择当前最小/最大的元素即可。

    代码如下:

    class Solution(object):
        def bagOfTokensScore(self, tokens, P):
            """
            :type tokens: List[int]
            :type P: int
            :rtype: int
            """
            tokens.sort()
            low = 0
            high = len(tokens) - 1
            res = 0
            point = 0
            while low <= high:
                if P >= tokens[low]:
                    point += 1
                    P -= tokens[low]
                    low += 1
                    res = max(res,point)
                elif point > 0:
                    point -= 1
                    P += tokens[high]
                    high -= 1
                else:
                    low += 1
            return res
  • 相关阅读:
    C#与SAP进行数据交互
    自动加减工单结存算法实现
    RDLC报表打印一维码
    调用存储过程通用类
    监听网络状态
    压缩及解压缩文件
    用Go造轮子-管理集群中的配置文件
    2015年总结
    浅析Go语言的Interface机制
    2014年总结
  • 原文地址:https://www.cnblogs.com/seyjs/p/10020528.html
Copyright © 2011-2022 走看看