本文涉及知识点
C++贪心
C++二分查找
C++算法:滑动窗口及双指针总结
LeetCode826. 安排工作以达到最大收益
你有 n 个工作和 m 个工人。给定三个数组: difficulty, profit 和 worker ,其中:
difficulty[i] 表示第 i 个工作的难度,profit[i] 表示第 i 个工作的收益。
worker[i] 是第 i 个工人的能力,即该工人只能完成难度小于等于 worker[i] 的工作。
每个工人 最多 只能安排 一个 工作,但是一个工作可以 完成多次 。
举个例子,如果 3 个工人都尝试完成一份报酬为 $1 的同样工作,那么总收益为 $3 。如果一个工人不能完成任何工作,他的收益为 $0 。
返回 在把工人分配到工作岗位后,我们所能获得的最大利润 。
示例 1:
输入: difficulty = [2,4,6,8,10], profit = [10,20,30,40,50], worker = [4,5,6,7]
输出: 100
解释: 工人被分配的工作难度是 [4,4,6,6] ,分别获得 [20,20,30,30] 的收益。
示例 2:
输入: difficulty = [85,47,57], profit = [24,66,99], worker = [40,25,25]
输出: 0
提示:
n == difficulty.length
n == profit.length
m == worker.length
1 <= n, m <= 104
1 <= difficulty[i], profit[i], worker[i] <= 105
二分查找+贪心
有如下性质:
任何工人,如果能完成工作,则一定完成工作。如果能完成多项工作,则完成价值最高的工作。
方法一:
枚举工人,计算能完成价值最高的工作。时间复杂度:O(mlogn)
如果工作a比份工作b:难度大,价值低,则一定存在最优解,不包括a,可以用决策包容性证明。即可以淘汰a,淘汰所有a后,价值和难度都有序。如果有模板直接使用。
方法二:
按工作价值从高到低排序。每份工作,如果某个工人能完成此任务,则完成此任务,并从setWork 中删除。
时间复杂度:O(nlogm)
multiset setWorker(worker.begin(),worker.end());
multimap<int, int,greater<>> mJob;
方法三2025年1月22 双指针
工人能力升序排序。工作难度也升序排序。iMax 记录当前工人能够完成的任务的最大收益。显然iMax单调变大。也可以将工作难度降序,当栈使用。
代码
核心代码
class Solution {
public:
int maxProfitAssignment(vector<int>& difficulty, vector<int>& profit, vector<int>& worker) {
multiset<int> setWorker(worker.begin(),worker.end());
multimap<int, int,greater<>> mJob;
for (int i = 0; i < profit.size(); i++) {
mJob.emplace(profit[i], difficulty[i]);
}
int ret = 0;
for ( auto& [profit, diff] : mJob) {
auto it = setWorker.lower_bound(diff);
ret += profit * distance(it,setWorker.end());
setWorker.erase(it, setWorker.end());
}
return ret;
}
};
单元测试
TEST_METHOD(TestMethod1)
{
difficulty = { 1,2 }, profit = { 1,1 }, worker = { 1,2 };
auto res = Solution().maxProfitAssignment(difficulty, profit, worker);
AssertEx(2, res);
}
TEST_METHOD(TestMethod2)
{
difficulty = { 2,1 }, profit = { 1,1 }, worker = { 1,2 };
auto res = Solution().maxProfitAssignment(difficulty, profit, worker);
AssertEx(2, res);
}
TEST_METHOD(TestMethod3)
{
difficulty = { 1}, profit = { 1}, worker = { 1,1 };
auto res = Solution().maxProfitAssignment(difficulty, profit, worker);
AssertEx(2, res);
}
TEST_METHOD(TestMethod11)
{
difficulty = { 2,4,6,8,10 }, profit = { 10,20,30,40,50 }, worker = { 4,5,6,7 };
auto res = Solution().maxProfitAssignment(difficulty, profit, worker);
AssertEx(100, res);
}
TEST_METHOD(TestMethod12)
{
difficulty = { 85,47,57 }, profit = { 24,66,99 }, worker = { 40,25,25 };
auto res = Solution().maxProfitAssignment(difficulty, profit, worker);
AssertEx(0, res);
}