安排工作以达到最大收益
难度:
标签:
题目描述
代码结果
运行时间: 66 ms, 内存: 18.5 MB
/*
* Problem statement:
* You have n jobs and m workers. Given three arrays: difficulty, profit, and worker, where:
* difficulty[i] indicates the difficulty of the ith job, profit[i] indicates the profit of the ith job.
* worker[i] is the ability of the ith worker, meaning that this worker can only complete a job with difficulty less than or equal to worker[i].
* Each worker can be assigned at most one job, but one job can be completed multiple times.
* Return the maximum profit we can achieve after assigning workers to jobs.
*/
import java.util.Arrays;
public class MaxProfitAssignmentStream {
public int maxProfitAssignment(int[] difficulty, int[] profit, int[] worker) {
// Combine difficulty and profit arrays into a single 2D array
int[][] jobs = new int[difficulty.length][2];
for (int i = 0; i < difficulty.length; i++) {
jobs[i][0] = difficulty[i];
jobs[i][1] = profit[i];
}
// Sort jobs by difficulty and worker by ability
Arrays.sort(jobs, (a, b) -> a[0] - b[0]);
Arrays.sort(worker);
// Use streams to find the maximum profit
int[] maxProfit = {0};
int[] best = {0};
int[] jobIndex = {0};
Arrays.stream(worker).forEach(w -> {
while (jobIndex[0] < jobs.length && w >= jobs[jobIndex[0]][0]) {
best[0] = Math.max(best[0], jobs[jobIndex[0]][1]);
jobIndex[0]++;
}
maxProfit[0] += best[0];
});
return maxProfit[0];
}
}
解释
方法:
题解首先将工作按照利润进行降序排序,如果利润相同则按难度升序排序。随后将工人能力也进行降序排序。使用贪心算法,从能力最强的工人开始,为每个工人分配他能够完成的利润最大的工作。这是通过一个指针i来维持当前能分配的最大利润的工作。如果工人的能力不足以完成当前i指向的工作,则i向后移动,直到找到该工人能完成的工作。这样可以确保每个工人都尽可能地获取最大利润。
时间复杂度:
O(n log n + m log m)
空间复杂度:
O(1)
代码细节讲解
🦆
在算法中,将工作按利润降序排序后,为何还需要在利润相同的情况下按难度升序排序?
▷🦆
对工人能力进行降序排序的原因是什么?如何确保这种排序方式能帮助实现最大利润?
▷🦆
算法中使用了贪心策略,这种策略在所有情况下都能保证找到最大利润吗?存在哪些可能的局限性?
▷🦆
在题解中提到,如果所有工作都不能由当前工人完成,则停止分配。这种处理方式是否可能导致后续有能力较低的工人错过可完成的工作?
▷