置頂

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

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

熱門文章

2026年10月19日 星期一

LeetCode 解題筆記:826. Most Profit Assigning Work

作者:王一哲
日期:2026年10月19日


LeetCode 題目連結:826. Most Profit Assigning Work

解題想法


中等難度題。題目給兩個長度為 $n ~(1 \leq n \leq 10^4)$ 的正整數陣列 $difficulty ~(1 \leq difficulty[i] \leq 10^5)$ 及 $profit ~(1 \leq profit[i] \leq 10^5)$,分別代表工作的困難度及利潤,以及一個長度為 $m ~(1 \leq n \leq 10^4)$ 的正整數陣列 $worker ~(1 \leq worker[i] \leq 10^5)$,代表工人的能力值。如果這個工人的能力值大於等於某一項工作的困難度,則這個工人可以承接這項工作,並取得對應的利潤。每個工人只能承接一項工作,同一項工作可以由多個工人承接,則最大利潤為何?

這題最直接的想法是先將 $profit$ 及 $difficulty$ 組成 tuple,先依照利潤由大到小排序,再依照困難度由小到大排序。接著用兩層 for 迴圈計算答案 $ans$,外層迴圈跑每個工人的能力 $w$,內層迴圈跑工作的利潤 $p$ 及困難度 $d$,如果某一項工作符合 $w \geq d$,可以承接這項工作,$ans += p$,中止迴圈。不過這樣跑的時間複雜度為 $O(n^2)$,很慢。

換一種想法,先將 $difficulty$ 及 $profit$ 組成 tuple,由小到大排序。再建立兩個陣列 $diff$ 及 $prof$,分別代表不重複的工作難度及對應的最大利潤,並且先放入 $0$ 避免空陣列造成的問題。用一個變數 $pmax$ 記錄目前的最高利潤。再用一層 for 迴圈填入 $diff$ 及 $prof$ 對應的資料。最後用一層 for 迴圈跑每個工人的能力 $w$,用內建的二分搜尋法工具從 $diff$ 之中找第一個大於、等於 $w$ 的工作索引值 $idx$,如果 $idx == len(diff)$ 代表這個工人可以承接任何工作,答案 $ans$ 加上利潤最大值;反之,再用一個 while 迴圈往回找第一個等於 $w$ 的工作,$ans$ 加上工作對應的利潤。這個寫法的時間複雜度為 $O(n \log n)$,速度快很多。

Python 程式碼


$O(n^2)$. Runtime: 4643 ms, beats 5.13%. Memory: 22.53 MB, beats 16.49%.
class Solution:
    def maxProfitAssignment(self, difficulty: list[int], profit: list[int], worker: list[int]) -> int:
        arr = [(p, d) for p, d in zip(profit, difficulty)]
        arr.sort(key = lambda x : (-x[0], x[1]))
        
        ans = 0
        for w in worker:
            for p, d in arr:
                if w >= d:
                    ans += p
                    break
        return ans


$O(log n)$. Runtime: 36 ms, beats 62.99%. Memory: 22.10 MB, beats 79.16%.
from bisect import bisect_left

class Solution:
    def maxProfitAssignment(self, difficulty: list[int], profit: list[int], worker: list[int]) -> int:
        arr = sorted((d, p) for d, p in zip(difficulty, profit))
        diff, prof = [0], [0]  # 不重複的工作難度及對應的最高利潤
        pmax = 0  # 目前任務可得的最高利潤
        for d, p in arr:
            pmax = max(pmax, p)  # 更新最高利潤
            if d > diff[-1]:  # 較高的難度
                diff.append(d)
                prof.append(pmax)
            elif d == diff[-1]:  # 相同的難度
                prof[-1] = pmax
        
        # 用工人的能力於 diff 之中搜尋可執行的工作及最高利潤
        n = len(diff)  # 長度
        ans = 0  # 答案
        for w in worker:
            idx = bisect_left(diff, w)
            if idx == n:  # 可以執行最難的工作
                ans += prof[-1]
            else:
                while diff[idx] > w: idx -= 1  # 往回找到小於、等於 w 的值
                ans += prof[idx]
        return ans


C++ 程式碼


$O(n^2)$. Runtime: 309 ms, beats 17.50%. Memory: 40.40 MB, beats 88.00%.
class Solution {
public:
    int maxProfitAssignment(vector<int>& difficulty, vector<int>& profit, vector<int>& worker) {
        int m = (int)difficulty.size();
        vector<pair<int, int>> arr (m);  // (利潤, 困難度)
        for(int i = 0; i < m; i++) {
            arr[i] = {profit[i], difficulty[i]};
        }
        sort(arr.begin(), arr.end(), [](pair<int, int> a, pair<int, int> b) {
            if (a.first == b.first) return a.second < b.second;
            return a.first > b.first;
        });

        int ans = 0;  // 答案
        for(int w : worker) {
            for(auto it : arr) {
                if (w >= it.second) {
                    ans += it.first;
                    break;
                }
            }
        }
        return ans;
    }
};


$O(log n)$. Runtime: 36 ms, beats 62.99%. Memory: 22.10 MB, beats 79.16%.
from bisect import bisect_left

class Solution:
    def maxProfitAssignment(self, difficulty: list[int], profit: list[int], worker: list[int]) -> int:
        arr = sorted((d, p) for d, p in zip(difficulty, profit))
        diff, prof = [0], [0]  # 不重複的工作難度及對應的最高利潤
        pmax = 0  # 目前任務可得的最高利潤
        for d, p in arr:
            pmax = max(pmax, p)  # 更新最高利潤
            if d > diff[-1]:  # 較高的難度
                diff.append(d)
                prof.append(pmax)
            elif d == diff[-1]:  # 相同的難度
                prof[-1] = pmax
        
        # 用工人的能力於 diff 之中搜尋可執行的工作及最高利潤
        n = len(diff)  # 長度
        ans = 0  # 答案
        for w in worker:
            idx = bisect_left(diff, w)
            if idx == n:  # 可以執行最難的工作
                ans += prof[-1]
            else:
                while diff[idx] > w: idx -= 1  # 往回找到小於、等於 w 的值
                ans += prof[idx]
        return ans


沒有留言:

張貼留言