日期:2026年11月11日
LeetCode 題目連結:3789. Minimum Cost to Acquire Required Items
解題想法
中等難度題。題目給 5 個整數,$cost1$ 代表單獨買 1 單位的物品 1 的價格,$cost2$ 代表單獨買 1 單位的物品 2 的價格,$costBoth$ 代表同時買 1 單位的物品 1 及 1 單位的物品 2 的價格,$need1$ 代表物品 1 需要買的數量,$need2$ 代表物品 2 需要買的數量,求買到需要的數量至少需要花多少錢?
這題考數學。先試著一起買 $need1, need2$ 之中最少的數量,假設量值為 $buyBoth$,選擇一起買 $costBoth$ 或分開買 $cost1 + cost2$ 之中比較省錢的方案,將金額加到答案 $ans$,再更新 $need1, need2$,減去已經購買的量 $buyBoth$。接下來買需求 1 剩下的量,如果 $need1 > 0$ 才需要計算,$ans$ 再加上 $costBoth, cost1$ 較低者乘以 $need1$,由於題目只要求最低花費,不需要計算多買的量,不用再更新 $need1$。最後買需求 2 剩下的量,如果 $need2 > 0$ 才需要計算,$ans$ 再加上 $costBoth, cost2$ 較低者乘以 $need2$。
Python 程式碼
Runtime: 0 ms, beats 100.00%. Memory: 19.22 MB, beats 71.58%.
class Solution:
def minimumCost(self, cost1: int, cost2: int, costBoth: int, need1: int, need2: int) -> int:
# 先試著一起買,選擇一起買或分開買之中比較省錢的方案
buyBoth = min(need1, need2) # 需求 1、2 較小的數字
ans = min(costBoth, cost1 + cost2) * buyBoth
# 更新需求量
need1 -= buyBoth
need2 -= buyBoth
# 買需求 1 剩下的量
if need1 > 0:
ans += min(costBoth, cost1) * need1
# 買需求 2 剩下的量
if need2 > 0:
ans += min(costBoth, cost2) * need2
return ans