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.
Example 1:
Input: n = 6, speed = [2,10,3,1,5,8], efficiency = [5,4,3,9,7,2], k = 2 Output: 60 Explanation: We have the maximum performance of the team by selecting engineer 2 (with speed=10 and efficiency=4) and engineer 5 (with speed=5 and efficiency=7). That is, performance = (10 + 5) * min(4, 7) = 60.
Example 2:
Input: n = 6, speed = [2,10,3,1,5,8], efficiency = [5,4,3,9,7,2], k = 3 Output: 68 Explanation: This is the same example as the first but k = 3. We can select engineer 1, engineer 2 and engineer 5 to get the maximum performance of the team. That is, performance = (2 + 10 + 5) * min(5, 4, 7) = 68.
Example 3:
Input: n = 6, speed = [2,10,3,1,5,8], efficiency = [5,4,3,9,7,2], k = 4 Output: 72
Constraints:
1 <= n <= 10^5speed.length == nefficiency.length == n1 <= speed[i] <= 10^51 <= efficiency[i] <= 10^81 <= k <= n
For a given efficiency, we pick all works with the same or better efficiency. If the number of workers is greater than k, we pick k fastest workers.
We greedily try each engineer from the most efficient one to the least one.
For each engineer:
- first try adding him to the team and add his
speed[i]to thesum. - If after the addition there are more than
kengineers in the team, pop the one with the leastspeed, and deduct hisspeedfromsum. - try to update the answer using
sum * speed[i].
The idea behind
// OJ: https://leetcode.com/problems/maximum-performance-of-a-team/
// Author: github.com/lzl124631x
// Time: O(NlogN)
// Space: O(N)
// Ref: https://leetcode.com/problems/maximum-performance-of-a-team/discuss/539687/JavaC%2B%2BPython-Priority-Queue
class Solution {
public:
int maxPerformance(int N, vector<int>& S, vector<int>& E, int K) {
vector<pair<int, int>> ps(N);
for (int i = 0; i < N; ++i) ps[i] = {E[i], S[i]};
sort(ps.begin(), ps.end());
long sum = 0, ans = 0;
priority_queue<int, vector<int>, greater<int>> pq;
for (int i = N - 1; i >= 0; --i) {
pq.push(ps[i].second);
sum += ps[i].second;
if (pq.size() > K) {
sum -= pq.top();
pq.pop();
}
ans = max(ans, sum * ps[i].first);
}
return ans % (int)(1e9+7);
}
};