跳至主要内容

826. Most Profit Assigning Work

  • 工人派遣工作,一人只能被指派一個工作,但是一個工作可以被做很多遍。
  • 初始化 {difficulty, profit} pair jobs
  • 排序 worker, jobs
  • 雙指針法搭配 Greedy 找最大獲利。
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)