置頂

我的 VPython 教學文件 (HackMD 版本)

VPython 教學文件目錄 安裝及測試 基本語法 等速度直線運動 自由落下 終端速度 水平抛射 使用For迴圈計算水平抛射資料 斜向抛射 圓周運動 簡諧運動 單擺 木塊彈簧系統分離 重力及簡諧 行星運動 相疊木塊 雙重簡諧運動 一維彈性碰撞 ...

熱門文章

2026年11月11日 星期三

LeetCode 解題筆記:3789. Minimum Cost to Acquire Required Items

作者:王一哲
日期: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


C++ 程式碼


Runtime: 0 ms, beats 100.00%. Memory: 9.08 MB, beats 98.82%.
class Solution {
public:
    long long minimumCost(int cost1, int cost2, int costBoth, int need1, int need2) {
        /* 先試著一起買,選擇一起買或分開買之中比較省錢的方案 */
        int buyBoth = min(need1, need2);  // 需求 1、2 較小的數字
        long long ans = (long long)min(costBoth, cost1 + cost2) * (long long)buyBoth;
        // 更新需求量
        need1 -= buyBoth;
        need2 -= buyBoth;
        
        /* 買需求 1 剩下的量 */
        if (need1 > 0) {
            ans += (long long)min(costBoth, cost1) * (long long)need1;
        }

        /* 買需求 2 剩下的量 */
        if (need2 > 0) {
            ans += (long long)min(costBoth, cost2) * (long long)need2;
        }

        return ans;
    }
};


C 語言程式碼


Runtime: 0 ms, beats 100.00%. Memory: 9.22 MB, beats 28.57%.
#define min(a, b) ((a) < (b) ? (a) : (b))
#define max(a, b) ((a) > (b) ? (a) : (b))

long long minimumCost(int cost1, int cost2, int costBoth, int need1, int need2) {
    /* 先試著一起買,選擇一起買或分開買之中比較省錢的方案 */
    int buyBoth = min(need1, need2);  // 需求 1、2 較小的數字
    long long ans = (long long)min(costBoth, cost1 + cost2) * (long long)buyBoth;
    // 更新需求量
    need1 -= buyBoth;
    need2 -= buyBoth;
    
    /* 買需求 1 剩下的量 */
    if (need1 > 0) {
        ans += (long long)min(costBoth, cost1) * (long long)need1;
    }

    /* 買需求 2 剩下的量 */
    if (need2 > 0) {
        ans += (long long)min(costBoth, cost2) * (long long)need2;
    }

    return ans;
}


沒有留言:

張貼留言