Leetcode--826. 安排工作以达到最大收益
有一些工作:difficulty[i]?表示第i個工作的難度,profit[i]表示第i個工作的收益。
現在我們有一些工人。worker[i]是第i個工人的能力,即該工人只能完成難度小于等于worker[i]的工作。
每一個工人都最多只能安排一個工作,但是一個工作可以完成多次。
舉個例子,如果3個工人都嘗試完成一份報酬為1的同樣工作,那么總收益為 $3。如果一個工人不能完成任何工作,他的收益為 $0 。
我們能得到的最大收益是多少?
示例:
輸入: 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] 的收益。
提示:
1 <= difficulty.length = profit.length <= 10000
1 <= worker.length <= 10000
difficulty[i], profit[i], worker[i]??的范圍是?[1, 10^5]
思路:
先將工人能力排序,再將工作按照酬勞排序
如果能力高的工人都做不了的工作,能力低的自然不用做了
class Solution {
? ? public int maxProfitAssignment(int[] difficulty, int[] profit, int[] worker) {
? ? ? ? int count=0;
? ? ? ? int[][] difficultAndProfit=new int[difficulty.length][2];
? ? ? ? for(int i=0;i<difficultAndProfit.length;i++){
? ? ? ? ? ? difficultAndProfit[i][0]=difficulty[i];
? ? ? ? ? ? difficultAndProfit[i][1]=profit[i];
? ? ? ? }
? ? ? ? //按難度排序二維數組
? ? ? ? Arrays.sort(difficultAndProfit, new Comparator<int[]>() {
? ? ? ? ? ? @Override
? ? ? ? ? ? public int compare(int[] o1, int[] o2) {
? ? ? ? ? ? ? ? return o1[0]-o2[0];
? ? ? ? ? ? }
? ? ? ? });
? ? ? ? //排序worker表
? ? ? ? Arrays.sort(worker);
? ? ? ? int workIndex=0;
? ? ? ? int count1=0;
? ? ? ? for(int i=0;i<worker.length;i++){
? ? ? ? ? ? for(int j=workIndex;j<difficultAndProfit.length;j++){
? ? ? ? ? ? ? ? if(worker[i]>=difficultAndProfit[j][0]){
? ? ? ? ? ? ? ? ? ? if(difficultAndProfit[j][1]>count1){
? ? ? ? ? ? ? ? ? ? ? ? count1=difficultAndProfit[j][1];
? ? ? ? ? ? ? ? ? ? }
? ? ? ? ? ? ? ? ? ? workIndex++;
? ? ? ? ? ? ? ? }
? ? ? ? ? ? ? ? else {
? ? ? ? ? ? ? ? ? ? break;
? ? ? ? ? ? ? ? }
? ? ? ? ? ? }
? ? ? ? ? ? count+=count1;
? ? ? ? }
? ? ? ? return count;
? ? }
}
總結
以上是生活随笔為你收集整理的Leetcode--826. 安排工作以达到最大收益的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 2021-07-24 KDD China
- 下一篇: 【剑指offer】面试题40:最小的k个