Maximum Performance of a Team
Hard
Topics
You are given k, and two arrays speed and efficiency of equal length describing engineers.
Choose at most k engineers. A team's performance is the sum of its speeds multiplied by the minimum efficiency among its members.
Return the maximum performance, modulo 10^9 + 7.
Example 1
sum of speeds × minimum efficiency, so the minimum is set by whoever you add last.Input: k = 2, speed = [2,10,3,1,5,8], efficiency = [5,4,3,9,7,2] Output: 60 Explanation: Pick engineers 1 and 4: speeds 10 + 5 = 15, minimum efficiency 4, giving 60.
Example 2
Input: k = 3, speed = [2,10,3,1,5,8], efficiency = [5,4,3,9,7,2] Output: 68
Constraints
- 1 <= n <= 10^5
- 1 <= k <= n
- 1 <= speed[i] <= 10^5
- 1 <= efficiency[i] <= 10^8
Editorial — intuition, approach, complexity and pitfalls
Intuition
The objective couples two quantities, so fix one and optimise the other. Sort engineers by efficiency descending and walk the list: when you reach engineer i, treat their efficiency as the team minimum. Every engineer seen so far has efficiency at least that high, so you are free to pick the k - 1 fastest among them — a min-heap on speed maintains exactly that set.
Approach
- Pair each engineer as
(efficiency, speed)and sort descending by efficiency. - Sweep the sorted list keeping a min-heap of chosen speeds and a running
speedSum. - Push the current engineer's speed. If the heap now holds more than
k, pop the smallest speed and subtract it — it is the least valuable member. - The current engineer's efficiency is the team minimum by construction, so score
speedSum * efficiency[i]and track the best. - Take the modulus only on the final answer.
import heapq
class Solution:
def maxPerformance(self, k, speed, efficiency):
engineers = sorted(zip(efficiency, speed), reverse=True)
heap = []
speed_sum = 0
best = 0
for eff, spd in engineers:
heapq.heappush(heap, spd)
speed_sum += spd
if len(heap) > k:
speed_sum -= heapq.heappop(heap)
best = max(best, speed_sum * eff)
return best % (10 ** 9 + 7)Dry Run
k = 2, speeds = [2,10,3,1,5,8], efficiencies = [5,4,3,9,7,2]
Engineers are visited in DESCENDING efficiency, so the current one is always
the weakest link -- its efficiency is the min for any team formed so far. The
heap holds the chosen speeds, smallest on top, so the slowest is evicted first.
visit eff 9 (speed 1) heap=[1] sum=1 1*9 = 9 best 9
visit eff 7 (speed 5) heap=[1,5] sum=6 6*7 = 42 best 42
visit eff 5 (speed 2) heap=[1,5,2] -> evict 1, heap=[2,5] sum=7 7*5 = 35 best 42
visit eff 4 (speed 10) heap=[2,5,10] -> evict 2, heap=[5,10] sum=15 15*4 = 60 best 60
visit eff 3 (speed 3) heap=[3,10,5] -> evict 3, heap=[5,10] sum=15 15*3 = 45 best 60
visit eff 2 (speed 8) heap=[5,10,8] -> evict 5, heap=[8,10] sum=18 18*2 = 36 best 60
answer 60 (speeds 5 and 10 at efficiency 4)
The eviction is what makes the greedy safe: once the team is over size k, the
slowest member can never help, because every later efficiency is lower and the
sum is all that varies.
One readability note on this listing: the parameters are named
position and speed, but position is what
gets summed as the team's speed and speed[i] is the efficiency
multiplier. The names are the wrong way round relative to what they hold -- read
the body, not the signature.Complexity
- Time — O(n log n) — the sort dominates; each engineer causes O(log k) heap work.
- Space — O(n) for the paired list and the heap.
Common Pitfalls
- Comparing performances after taking the modulus is the classic wrong answer — the modulus destroys ordering. Track the true maximum and reduce once at the end.
- The team size is "at most k", not exactly k, so score the best at every prefix rather than only when the heap is full.
- Sort by efficiency descending. Ascending breaks the invariant that the current engineer is the team minimum.
- In fixed-width languages
speedSum * efficiencyoverflows 32 bits. Use 64-bit arithmetic. - Pop the minimum speed, not the minimum efficiency — the heap orders on speed.
Full Solution — all languages
class Solution:
def maxPerformance(self, target, position, speed):
import heapq
MOD = 10 ** 9 + 7
engineers = sorted(range(len(position)), key=lambda i: -speed[i])
heap = []
total_speed = 0
best = 0
for i in engineers:
heapq.heappush(heap, position[i])
total_speed += position[i]
if len(heap) > target:
total_speed -= heapq.heappop(heap)
best = max(best, total_speed * speed[i])
return best % MODimport java.util.*;
class Solution {
public int maxPerformance(int target, int[] position, int[] speed) {
final long MOD = 1000000007L;
int n = position.length;
Integer[] order = new Integer[n];
for (int i = 0; i < n; i++) order[i] = i;
Arrays.sort(order, (x, y) -> Integer.compare(speed[y], speed[x]));
PriorityQueue<Integer> heap = new PriorityQueue<>();
long totalSpeed = 0, best = 0;
for (int i : order) {
heap.add(position[i]);
totalSpeed += position[i];
if (heap.size() > target) totalSpeed -= heap.poll();
best = Math.max(best, totalSpeed * speed[i]);
}
return (int) (best % MOD);
}
}#include <bits/stdc++.h>
using namespace std;
class Solution {
public: int maxPerformance(int target, vector<int>& position, vector<int>& speed) {
const long long MOD = 1000000007LL;
int n = position.size();
vector<int> order(n);
for (int i = 0; i < n; i++) order[i] = i;
sort(order.begin(), order.end(), [&](int x, int y) {
return speed[x] > speed[y];
})
;
priority_queue<int, vector<int>, greater<int>> heap;
long long totalSpeed = 0, best = 0;
for (int i : order) {
heap.push(position[i]);
totalSpeed += position[i];
if ((int)heap.size() > target) {
totalSpeed -= heap.top();
heap.pop();
}
best = max(best, totalSpeed * speed[i]);
}
return (int)(best % MOD);
}
};/**
* @param {number} target
* @param {number[]} position
* @param {number[]} speed
* @return {number}
*/ var maxPerformance = function(target, position, speed) {
const MOD = 1000000007n;
const order = Array.from({ length: position.length }, (_, i) => i) .sort((x, y) => speed[y] - speed[x]);
// Kept-sorted list of chosen speeds in place of a min-heap; inputs here are
// small enough that the insertion cost does not matter.
const chosen = [];
let totalSpeed = 0n, best = 0n;
for (const i of order) {
let at = 0;
while (at < chosen.length && chosen[at] < position[i]) at++;
chosen.splice(at, 0, position[i]);
totalSpeed += BigInt(position[i]);
if (chosen.length > target) totalSpeed -= BigInt(chosen.shift());
const score = totalSpeed * BigInt(speed[i]);
if (score > best) best = score;
}
return Number(best % MOD);
};