经典贪心,826. 安排工作以达到最大收益

目录

一、题目

1、题目描述

2、接口描述

python3

cpp

3、原题链接

二、解题报告

1、思路分析

2、复杂度

3、代码详解

python3

cpp


一、题目

1、题目描述

你有 n 个工作和 m 个工人。给定三个数组: difficultyprofit 和 worker ,其中:

  • difficulty[i] 表示第 i 个工作的难度,profit[i] 表示第 i 个工作的收益。
  • worker[i] 是第 i 个工人的能力,即该工人只能完成难度小于等于 worker[i] 的工作。

每个工人 最多 只能安排 一个 工作,但是一个工作可以 完成多次 。

  • 举个例子,如果 3 个工人都尝试完成一份报酬为 $1 的同样工作,那么总收益为 $3 。如果一个工人不能完成任何工作,他的收益为 $0 。

返回 在把工人分配到工作岗位后,我们所能获得的最大利润 

2、接口描述

python3
class Solution:
    def maxProfitAssignment(self, difficulty: List[int], profit: List[int], worker: List[int]) -> int:
cpp
class Solution {
public:
    int maxProfitAssignment(vector<int>& difficulty, vector<int>& profit, vector<int>& worker) {

    }
};

3、原题链接

826. 安排工作以达到最大收益


二、解题报告

1、思路分析

很经典的贪心问题

我们将任务按照双关键字升序排序,第一关键字:难度,第二关键字:利润

将员工也升序排序

然后顺序遍历员工,用一个指针维护当前能够干的任务

排序后有个好处,前面员工能干的,后面的员工也能干

我们遍历员工的时候不断地把能干的任务拿进来,然后这个员工应该干当前能干的任务当中利润最大那个

2、复杂度

时间复杂度: O(nlogn + mlogm)空间复杂度:O(n)

3、代码详解

python3
from sortedcontainers import SortedList
class Solution:
    def maxProfitAssignment(self, difficulty: List[int], profit: List[int], worker: List[int]) -> int:
        n = len(difficulty)
        ma = i = ret = 0
        dp = sorted(list(zip(difficulty, profit)))
        
        for w in sorted(worker):
            while i < n and dp[i][0] <= w:
                ma = max(dp[i][1], ma)
                i += 1
            ret += ma
        return ret
cpp
class Solution {
public:
    int maxProfitAssignment(vector<int>& difficulty, vector<int>& profit, vector<int>& worker) {
        vector<pair<int, int>> dp;
        int n = difficulty.size();
        int i = 0, ma = 0, ret = 0;
        for (i = 0; i < n; i ++) dp.emplace_back(difficulty[i], profit[i]);
        sort(dp.begin(), dp.end());
        sort(worker.begin(), worker.end());
        i = 0;
        for (int w : worker) {
            while (i < n && dp[i].first <= w) ma = max(ma, dp[i ++].second);
            ret += ma;
        }
        return ret;
    }
};

  • 4
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

EQUINOX1

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值