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^5
speed.length == n
efficiency.length == n
1 <= speed[i] <= 10^5
1 <= efficiency[i] <= 10^8
1 <= k <= n
Solution: Greedy + Sliding Window
- Sort engineers by their efficiency in descending order.
- For each window of K engineers (we can have less than K people in the first k-1 windows), ans is sum(speed) * min(efficiency).
Time complexity: O(nlogn) + O(nlogk)
Space complexity: O(n)
C++
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 |
// Author: Huahua class Solution { public: int maxPerformance(int n, vector<int>& speed, vector<int>& efficiency, int k) { vector<pair<int, int>> es; for (int i = 0; i < n; ++i) es.push_back({efficiency[i], speed[i]}); sort(rbegin(es), rend(es)); priority_queue<int, vector<int>, greater<int>> q; long sum = 0; long ans = 0; for (int i = 0; i < n; ++i) { if (i >= k) { sum -= q.top(); q.pop(); } sum += es[i].second; q.push(es[i].second); ans = max(ans, sum * es[i].first); } return ans % static_cast<int>(1e9 + 7); } }; |
Python3
1 2 3 4 5 6 7 8 9 10 11 12 13 |
# Author: Huahua class Solution: def maxPerformance(self, n: int, speed: List[int], efficiency: List[int], k: int) -> int: speeds = 0 ans = 0 q = [] for e, s in sorted(zip(efficiency, speed), reverse=True): if len(q) >= k: speeds -= heapq.heappop(q) speeds += s heapq.heappush(q, s) ans = max(ans, speeds * e) return ans % (10**9 + 7) |
请尊重作者的劳动成果,转载请注明出处!花花保留对文章/视频的所有权利。
如果您喜欢这篇文章/视频,欢迎您捐赠花花。
If you like my articles / videos, donations are welcome.
Be First to Comment