【LeetCode】948. Bag of Tokens 解題報告(Python)
阿新 • • 發佈:2018-11-27
作者: 負雪明燭
id: fuxuemingzhu
個人部落格: http://fuxuemingzhu.cn/
目錄
題目地址:https://leetcode.com/problems/bag-of-tokens/description/
題目描述
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]
- If we have at least
token[i]
power, we may play the token face up, losingtoken[i]
power, and gaining1
point. - If we have at least
1
point, we may play the token face down, gainingtoken[i]
power, and losing1
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:
- tokens.length <= 1000
- 0 <= tokens[i] < 10000
- 0 <= P < 10000
題目大意
有個power,現在有兩種操作:
- 當power超過token[i]的時候,可以把token[i]進行翻轉成正面,然後得到了1個點;
- 當至少有1個點的時候,可以把任何一個token[i]進行翻轉成反面,然後丟失1個點。
可以認為token在剛開始的時候既不是正面也不是反面。
問最後能獲得的最多的點數是多少。
解題方法
貪心演算法
使用了兩個指標,左邊指向翻成正面的token,右邊指向翻成反面的token.
首先,對token先排序。
第一步,我們用現在所有的power把左邊的都翻成正面,同時獲得了一些點。這一步之後,我們使用power貪心地獲得了所有的點數。
第二步,我們看右邊能翻轉多少個反面,這個能獲得Power,所以我們使用的點數換取了更多的power.
這兩步來回走的話,就能獲得更多的Points。
需要注意的是,如果剩餘的token只有一個的時候,我們是不把它換成power的。
class Solution(object):
def bagOfTokensScore(self, tokens, P):
"""
:type tokens: List[int]
:type P: int
:rtype: int
"""
print(tokens)
tokens.sort()
N = len(tokens)
left, right = 0, N - 1
points = 0
remain = N
while left < N and P >= tokens[left]:
P -= tokens[left]
points += 1
left += 1
remain -= 1
if left == 0 or left == N: return points
while points > 0 and remain > 1:
P += tokens[right]
right -= 1
points -= 1
remain -= 1
while left <= right and P >= tokens[left]:
P -= tokens[left]
points += 1
left += 1
remain -= 1
return points
日期
2018 年 11 月 24 日 —— 週日開始!一週就過去了~