一、题目描述
There are n engineers numbered from 1 to n and two arrays: speed and efficiency, where speed[i] and efficiency[i] represent the speed and efficiency for the i-th engineer respectively. Return the maximum performance of a team composed of at most k engineers, since the answer can be a huge number, return this modulo 10^9 + 7.
The performance of a team is the sum of their engineers’ speeds multiplied by the minimum efficiency among their engineers.
输入:n = 6, speed = [2,10,3,1,5,8], efficiency = [5,4,3,9,7,2], k = 2
输出:60
解释:
我们选择工程师 2(speed=10 且 efficiency=4)和工程师 5(speed=5 且 efficiency=7)。
他们的团队表现值为 performance = (10 + 5) * min(4, 7) = 60 。
题意:当两种方案的 efficiency 相等时,speed 之和更大的方案显然更优。问题转化成了如何快速求出每种 efficiency 的最优方案。
算法
- 每个人按照效率 e 进行降序排列。
- 在数组种选取 k 个最大的 speed。
public int maxPerformance(int n, int[] speed, int[] efficiency, int k) {
int[][] pair = new int[n][2];
for (int i = 0; i < n; i++) {
pair[i][0] = speed[i];
pair[i][1] = efficiency[i];
}
Arrays.sort(pair, (e1, e2) -> e2[1] - e1[1]);
PriorityQueue<Integer> pQ = new PriorityQueue<>();
long max = 0, sd = 0;
for (int i = 0; i < n; i++) {
pQ.add(pair[i][0]);
sd += pair[i][0];
if (pQ.size() > k) {
sd -= pQ.poll();
}
max = Math.max(max, sd * pair[i][1]);
}
return (int)(max % ((int)1e9 + 7));
}
复杂度分析
- 时间复杂度: ,
- 空间复杂度: ,