You are given two integers n
and k
and two integer arrays speed
and efficiency
both of length n
. There are n
engineers numbered from 1
to n
. speed[i]
and efficiency[i]
represent the speed and efficiency of the ith
engineer respectively.
Choose at most k
different engineers out of the n
engineers to form a team with the maximum performance.
The performance of a team is the sum of their engineers' speeds multiplied by the minimum efficiency among their engineers.
Return the maximum performance of this team. Since the answer can be a huge number, return it modulo 109 + 7
.
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 <= k <= n <= 105
speed.length == n
efficiency.length == n
1 <= speed[i] <= 105
1 <= efficiency[i] <= 108
class Solution:
def maxPerformance(self, n: int, speed: List[int], efficiency: List[int], k: int) -> int:
team = [(s, e) for s, e in zip(speed, efficiency)]
team.sort(key=lambda x: -x[1])
q = []
t = 0
ans = 0
mod = int(1e9) + 7
for s, e in team:
t += s
ans = max(ans, t * e)
heappush(q, s)
if len(q) >= k:
t -= heappop(q)
return ans % mod
class Solution {
public int maxPerformance(int n, int[] speed, int[] efficiency, int k) {
int[][] team = new int[n][2];
for (int i = 0; i < n; ++i) {
team[i] = new int[]{speed[i], efficiency[i]};
}
Arrays.sort(team, (a, b) -> b[1] - a[1]);
PriorityQueue<Integer> q = new PriorityQueue<>((a, b) -> a - b);
long t = 0;
long ans = 0;
int mod = (int) 1e9 + 7;
for (int[] x : team) {
int s = x[0], e = x[1];
t += s;
ans = Math.max(ans, t * e);
q.offer(s);
if (q.size() >= k) {
t -= q.poll();
}
}
return (int) (ans % mod);
}
}
class Solution {
public:
int maxPerformance(int n, vector<int>& speed, vector<int>& efficiency, int k) {
vector<pair<int, int>> team;
for (int i = 0; i < n; ++i) team.push_back({-efficiency[i], speed[i]});
sort(team.begin(), team.end());
priority_queue<int, vector<int>, greater<int>> q;
long long ans = 0;
int mod = 1e9 + 7;
long long t = 0;
for (auto& x : team)
{
int s = x.second, e = -x.first;
t += s;
ans = max(ans, e * t);
q.push(s);
if (q.size() >= k)
{
t -= q.top();
q.pop();
}
}
return (int) (ans % mod);
}
};