To maximize profit, assign the most profitable tasks to the most skilled workers. Sort both arrays and pair the largest profits with the largest skills.
classSolution {
public:int maxProfitAssignment(vector<int>& profit, vector<int>& worker) {
sort(profit.rbegin(), profit.rend());
sort(worker.rbegin(), worker.rend());
int n = min(profit.size(), worker.size()), ans =0;
for (int i =0; i < n; ++i) ans += profit[i] * worker[i];
return ans;
}
};
1
2
3
4
5
6
7
8
9
10
11
classSolution {
publicintmaxProfitAssignment(int[] profit, int[] worker) {
Arrays.sort(profit);
Arrays.sort(worker);
int n = Math.min(profit.length, worker.length), ans = 0;
for (int i = 0; i < n; i++) {
ans += profit[profit.length-1-i]* worker[worker.length-1-i];
}
return ans;
}
}
1
2
3
4
5
6
7
8
classSolution:
defmaxProfitAssignment(self, profit: list[int], worker: list[int]) -> int:
profit.sort(reverse=True)
worker.sort(reverse=True)
ans =0for p, w in zip(profit, worker):
ans += p * w
return ans