You have n
jobs and m
workers. You are given three arrays: difficulty
, profit
, and worker
where:
difficulty[i]
andprofit[i]
are the difficulty and the profit of theith
job, andworker[j]
is the ability ofjth
worker (i.e., thejth
worker can only complete a job with difficulty at mostworker[j]
).
Every worker can be assigned at most one job, but one job can be completed multiple times.
- For example, if three workers attempt the same job that pays
$1
, then the total profit will be$3
. If a worker cannot complete any job, their profit is$0
.
Return the maximum profit we can achieve after assigning the workers to the jobs.
Example 1:
Input: difficulty = [2,4,6,8,10], profit = [10,20,30,40,50], worker = [4,5,6,7] Output: 100 Explanation: Workers are assigned jobs of difficulty [4,4,6,6] and they get a profit of [20,20,30,30] separately.
思路: 把job按照difficulty 从小到大排序,然后每个woker去扫,同时记录最大profit,最后相加;
O(n logn + m * n );
class Solution {
class Node {
public int difficulty;
public int profit;
public Node(int difficulty, int profit) {
this.difficulty = difficulty;
this.profit = profit;
}
}
public int maxProfitAssignment(int[] difficulty, int[] profit, int[] worker) {
int n = difficulty.length;
Node[] nodes = new Node[n];
for(int i = 0; i < difficulty.length; i++) {
nodes[i] = new Node(difficulty[i], profit[i]);
}
Arrays.sort(nodes, (a, b) -> a.difficulty - b.difficulty);
int res = 0;
for(int i = 0; i < worker.length; i++) {
int j = 0;
int curmax = 0;
while(j < nodes.length && nodes[j].difficulty <= worker[i]) {
curmax = Math.max(curmax, nodes[j].profit);
j++;
}
res += curmax;
}
return res;
}
}
思路2:用dp来pre compute,先bucket记录每个diffucuty能够达到的profit,然后记录一下到目前为止的最大profit,然后woker去取最大值,加起来就是答案;O(N)
class Solution {
public int maxProfitAssignment(int[] difficulty, int[] profit, int[] worker) {
int[] dp = new int[100001];
for(int i = 0; i < difficulty.length; i++) {
int index = difficulty[i];
dp[index] = Math.max(dp[index], profit[i]);
}
for(int i = 1; i < dp.length; i++) {
dp[i] = Math.max(dp[i - 1], dp[i]);
}
int res = 0;
for(int i = 0; i < worker.length; i++) {
res += dp[worker[i]];
}
return res;
}
}