日期:2026年6月1日
LeetCode 題目連結:2144. Minimum Cost of Buying Candies With Discount
解題想法
簡單難度的題目。題目的意思是糖果買二送一,如果買兩顆糖果,其中較低的價格為 $p$,則可以免費拿一顆價格小於等於 $p$ 的糖果。題目會給一組糖果的價格,要計算得到所有糖果的最低成本。我的作法是將所有價格由高到低排序,再用一個 while 迴圈,從索引值 $i$ 開始往後處理到所有的糖果數量 $n$。假設總成本為 $total$,在 while 迴圈之中,每次先加上第 $i$ 個糖果的價格,然後將 $i+1$;如果此時 $i < n$,加上第 $i$ 個糖果的價格,然後將 $i+1$;如果此時 $i < n$,因為可以免費取得這顆糖果,直接將 $i+1$。跑完 while 迴圈之後直接回傳 $total$。
Python 程式碼
Runtime: 0 ms, beats 100%. Memory: 19.35 MB, beats 15.37%.
class Solution:
def minimumCost(self, cost: List[int]) -> int:
cost.sort(reverse=True)
ans = 0
n = len(cost)
i = 0
while i < n:
ans += cost[i]
i += 1
if i < n:
ans += cost[i]
i += 1
if i < n:
i += 1
return ans
C++ 程式碼
Runtime: 0 ms, beats 100%. Memory: 14.14 MB, beats 77.90%.
class Solution {
public:
int minimumCost(vector<int>& cost) {
sort(cost.begin(), cost.end(), greater<int> ());
int total = 0, i = 0, n = (int)cost.size();
while(i < n) {
total += cost[i];
i++;
if (i < n) {
total += cost[i];
i++;
}
if (i < n) i++;
}
return total;
}
};
沒有留言:
張貼留言