置頂

GeoGebra 文章目錄

GeoGebra 文章目錄  更新日期:2018/2/8 我將 GeoGebra 相關的文章及檔案連結都整理在這篇裡,之後如果有新的文章也會同時更新這個目錄。上傳到 GeoGebraTube 的檔案,我有試著用 Google Chrome 63.0.3239.13...

熱門文章

2026年6月21日 星期日

LeetCode 解題筆記:1833. Maximum Ice Cream Bars

作者:王一哲
日期:2026年6月21日


LeetCode 題目連結:1833. Maximum Ice Cream Bars

解題想法


寫起來像是簡單題的中等難度題。題目給定手上的現金 $coins$、冰淇淋的價格 $costs$,可以用任意順序購買冰淇淋,要找出最多可以購買幾支冰淇淋。只要先將 $costs$ 排序,再用 for 迴圈依序取出每支冰淇淋的價格 $cost$,如果 $coins \geq cost$,可以購買這支冰淇淋,將數量 $cnt += 1$,$coins -= cost$;反之,無法購買,中止迴圈。也可以用最小優先佇列 $pq$ 儲存價格,用 while 迴圈比較 $pq[0]$ 與 $coins$,如果 $coins \geq pq[0]$ 可以購買這支冰淇淋,移除 $pq[0]$、更新 $coins$ 及 $cnt$;跑完 while 迴圈之後回傳 $cnt$。

Python 程式碼


排序。Runtime: 79 ms, beats 69.30%. Memory: 30.83 MB, beats 70.23%.
class Solution:
    def maxIceCream(self, costs: List[int], coins: int) -> int:
        costs.sort()
        cnt = 0
        for cost in costs:
            if coins >= cost:
                coins -= cost
                cnt += 1
            else:
                break
        return cnt

最小優先佇列。Runtime: 43 ms, beats 94.73%. Memory: 32.00 MB, beats 66.20%.
import heapq

class Solution:
    def maxIceCream(self, costs: List[int], coins: int) -> int:
        heapq.heapify(costs)
        cnt = 0
        while costs and coins >= costs[0]:
            coins -= heapq.heappop(costs)
            cnt += 1
        return cnt


C++ 程式碼


排序。Runtime: 43 ms, beats 17.61%. Memory: 80.32 MB, beats 37.51%.
class Solution {
public:
    int maxIceCream(vector<int>& costs, int coins) {
        sort(costs.begin(), costs.end());
        int cnt = 0;
        for(int cost : costs) {
            if (coins >= cost) {
                coins -= cost;
                cnt++;
            } else {
                break;
            }
        }
        return cnt;
    }
};

最小優先佇列。Runtime: 36 ms, beats 42.67%. Memory: 83.66 MB, beats 28.30%.
class Solution {
public:
    int maxIceCream(vector<int>& costs, int coins) {
        priority_queue<int, vector<int>, greater<int>> pq (costs.begin(), costs.end());
        int cnt = 0;
        while(!pq.empty() && coins >= pq.top()) {
            coins -= pq.top();
            pq.pop();
            cnt++;
        }
        return cnt;
    }
};


沒有留言:

張貼留言