↓快轉到主要內容
  1. LeetCode/

LeetCode 948: Bag of Tokens

·1 分鐘· ·
LeetCode Medium Two-Pointers Greedy Sorting Array
Wei Yi Chung
作者
Wei Yi Chung
Working at the contributing of open source, distributed systems, and data engineering.
目錄

基本資料
#

難易度: medium 第一次嘗試:2026-01-24

  • 提交紀錄:Wrong Answer → Time Limit Exceeded → Accepted

解題思路
#

每個 token 只能用一次,翻正面是「花能量換 1 分」,翻背面是「花 1 分換能量」。貪心:

  • 換分數時,用最便宜的 token(左端)。
  • 換能量時,用最貴的 token(右端)。

排序後用對撞指針:

  1. 能量夠買左端:買下,分數 +1,更新最高分。
  2. 不夠但分數 > 0:賣掉右端,換回能量。
  3. 兩個都不行:停止。

答案是過程中的最高分,因為最後一步可能是賣掉 token 讓分數下降。

我的嘗試
#

  1. 第一版 WA:沒檢查分數就翻背面,分數可以變成負的。例如 tokens = [1, 3, 9]、power = 0:一個都買不起,答案是 0;這版先用負分換到 9 點能量,再買 1 和 3,回傳 1。
  2. 第二版 TLE:加上 score > 0 的條件,但兩個條件都不成立時沒有 break,指針不動,無窮迴圈。例如 tokens = [4, 7, 9]、power = 1。

正確解法
#

class Solution:
    def bagOfTokensScore(self, tokens: List[int], power: int) -> int:
        tokens.sort()
        left, right = 0, len(tokens) - 1
        score = best = 0
        while left <= right:
            if power >= tokens[left]:
                power -= tokens[left]
                left += 1
                score += 1
                best = max(best, score)
            elif score > 0:
                power += tokens[right]
                right -= 1
                score -= 1
            else:
                break
        return best

複雜度
#

時間 O(n log n),空間 O(1)(不算排序)。

要特別避免的錯誤
#

  • 分數是 0 時翻背面。
  • 兩個動作都做不了時忘記 break。
  • 回傳最後的分數而不是最高分。

面試口說整理
#

我把 token 排序,用最便宜的換分數、最貴的換能量。能量夠就買左端,不夠但有分數就賣右端,兩個都不行就停。最後可能是賣掉 token 讓分數下降,所以要記錄過程中的最高分。時間 O(n log n)。

相關文章

LeetCode 1877: Minimize Maximum Pair Sum in Array
·1 分鐘
LeetCode Medium Two-Pointers Greedy Sorting Array
LeetCode 1877 解題筆記:排序後最小配最大、次小配次大,對撞指針取配對和的最大值
LeetCode 2410: Maximum Matching of Players With Trainers
·1 分鐘
LeetCode Medium Two-Pointers Greedy Sorting Array
LeetCode 2410 解題筆記:兩邊都排序後,用同向雙指針讓最弱的球員配最小的、夠用的教練
LeetCode 1498: Number of Subsequences That Satisfy the Given Sum Condition
·2 分鐘
LeetCode Medium Two-Pointers Sorting Binary-Search Array
LeetCode 1498 解題筆記:子序列只看最小值和最大值,排序後順序無關;固定最小值 nums[left],中間的元素任意選,共 2^(right - left) 種
LeetCode 923: 3Sum With Multiplicity
·3 分鐘
LeetCode Medium Two-Pointers Sorting Hash-Table Counting Array
LeetCode 923 解題筆記:排序後固定第一個數、對撞指針找另外兩個;兩端值相同時用組合數一次算完,不同時把兩端各自的重複數相乘
LeetCode 825: Friends Of Appropriate Ages
·2 分鐘
LeetCode Medium Two-Pointers Sorting Binary-Search Array
LeetCode 825 解題筆記:排序後,每個人能送出邀請的對象是年齡落在 (0.5 × age + 7, age] 的一段區間,用兩個同向指針維護區間再扣掉自己
LeetCode 3413: Maximum Coins From K Consecutive Bags
·2 分鐘
LeetCode Medium Sliding-Window Greedy Sorting Prefix-Sum Binary-Search Array
LeetCode 3413 解題筆記:最佳的 k 個袋子,一定有一端對齊某段的端點;分別算「左端對齊段的起點」和「右端對齊段的終點」(鏡像後重用同一個函式)