Maximum Performance of a Team

Performance = sum(speed) * min(efficiency); sort by efficiency desc, keep top-k speeds.

Hard
Time O(n log n) Space O(n)
LeetCode
6 min read
top-k heaps sorting

Problem#

Each engineer has speed[i] and efficiency[i]. Pick at most k engineers. Performance = sum(speed of picked) * min(efficiency of picked). Maximize, modulo 10⁹ + 7.

Examples#

  • n = 6, speed = [2,10,3,1,5,8], efficiency = [5,4,3,9,7,2], k = 260

Constraints#

  • 1 <= k <= n <= 10^5.

Approach#

Sort by efficiency descending. Iterate; the current efficiency is the team min. Maintain a min-heap of speeds size ≤ k holding the best speeds seen. After adding each candidate, compute sumSpeed * curEfficiency and track the max.

Solution#

Maximum Performance of a Team
class Solution {
public:
int maxPerformance(int n, vector<int>& speed, vector<int>& efficiency, int k) {
const int MOD = 1'000'000'007;
vector<pair<int,int>> w(n);
for (int i = 0; i < n; ++i) w[i] = {efficiency[i], speed[i]};
sort(w.begin(), w.end(), greater<>());
priority_queue<int, vector<int>, greater<int>> pq;
long long sumSpeed = 0, best = 0;
for (auto& [e, s] : w) {
sumSpeed += s;
pq.push(s);
if ((int)pq.size() > k) { sumSpeed -= pq.top(); pq.pop(); }
best = max(best, sumSpeed * e);
}
return best % MOD;
}
};

Editorial#

Iterating in efficiency-descending order means the current engineer’s efficiency is the minimum among all candidates considered so far — the team’s “min efficiency” if they’re included. To maximize speed sum at that min, keep the top-k speeds. The heap operations dominate; modulo is applied only at the end (use long long everywhere intermediate).

Complexity#

  • Time: O(n log n).
  • Space: O(n).

Concept revision#

Search ESC

Keyboard shortcuts

Shortcuts are disabled while typing in inputs.