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
题目 最多选k个工程师,求最大工作绩效sum(efficiencys
)*min(speed)。
n选k的可能性有n!/k!种。需要进行一定的转换。对efficiency作为参数排序后不会起到任何作用。对speed排序后,只需要得到大于speed[i]的max(sum(efficiencys))即可。可以使用一个堆实现。代码如下:
class Solution(object):
def maxPerformance(self, n, speed, efficiency, k):
"""
:type n: int
:type speed: List[int]
:type efficiency: List[int]
:type k: int
:rtype: int
"""
if k == 1:
return max([speed[i]*efficiency[i] for i in range(n)])%(10**9 + 7)
sortedWorker = sorted([[efficiency[i],speed[i]] for i in range(n)])
heap = []
totalSpeed = 0
ret = 0
for i in range(n-1,n-k,-1):
heapq.heappush(heap,sortedWorker[i][1]) # 获取最大的k-1的总值
totalSpeed += sortedWorker[i][1]
ret = max(ret,totalSpeed*sortedWorker[i][0]) # 选择低于k的最大值
for i in range(n-k,-1,-1):
ret = max(ret,sortedWorker[i][0]*(totalSpeed+sortedWorker[i][1]))
if sortedWorker[i][1] > heap[0]: #有更优的选择
totalSpeed += sortedWorker[i][1] - heap[0]
heapq.heappop(heap)
heapq.heappush(heap,sortedWorker[i][1])
return ret%(10**9 + 7)