826. Most Profit Assigning Work

class Solution {
public:
    int maxProfitAssignment(vector<int>& difficulty, vector<int>& profit, vector<int>& worker)
    {
        int n = difficulty.size();

        // {difficulty, profit} pair
        vector<pair<int, int>> jobs;

        for (int i = 0; i < n; ++i)
        {
            jobs.push_back({difficulty[i], profit[i]});
        }

        sort(jobs.begin(), jobs.end());
        sort(worker.begin(), worker.end());

        // 雙指針法
        int res = 0;
        int i = 0;
        int cur = 0;
        for (auto w : worker)
        {
            while (i < n && w >= jobs[i].first)
            {
                cur = max(cur, jobs[i++].second);
            }
            res += cur;
        }
        return res;
    }
};
  • T: O(NlogN+MlogM)O(N \cdot \log N + M \cdot \log M)
  • S: O(N)O(N)