1383. Maximum Performance of a Team
Weekly Contest 180. Referred to this post.
class Solution {
public int maxPerformance(int n, int[] speed, int[] efficiency, int k) {
int MOD = (int) (1e9 + 7);
int[][] engineers = new int[speed.length][2];
for (int i = 0; i < speed.length; i++) {
engineers[i] = new int[]{speed[i], efficiency[i]};
}
// Sort efficiency in descending order.
Arrays.sort(engineers, new Comparator<int[]> () {
@Override
public int compare(int[] o1, int[] o2) {
return o2[1] - o1[1];
}
});
// Maintain a pq to track of the minimum speed in the group.
PriorityQueue<Integer> pq = new PriorityQueue<>(k);
long res = Long.MIN_VALUE;
long totalSpeed = 0;
for (int[] engineer : engineers) {
if (pq.size() == k) {
totalSpeed -= pq.poll(); // layoff the one with min speed
}
pq.add(engineer[0]);
totalSpeed = (totalSpeed + engineer[0]);
res = Math.max(res, (totalSpeed * engineer[1]));
}
return (int) (res % MOD);
}
}