1383. Maximum Performance of a Team

# 1383. Maximum Performance of a Team#

## 题目 #

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`

## 解题思路 #

• 题目要求返回最大团队表现值，表现值需要考虑速度的累加和，和效率的最小值。即使速度快，效率的最小值很小，总的表现值还是很小。先将效率从大到小排序。从效率高的工程师开始选起，遍历过程中维护一个大小为 k 的速度最小堆。每次遍历都计算一次团队最大表现值。扫描完成，最大团队表现值也筛选出来了。具体实现见下面的代码。

## 代码 #

``````package leetcode

import (
"container/heap"
"sort"
)

func maxPerformance(n int, speed []int, efficiency []int, k int) int {
indexes := make([]int, n)
for i := range indexes {
indexes[i] = i
}
sort.Slice(indexes, func(i, j int) bool {
return efficiency[indexes[i]] > efficiency[indexes[j]]
})
ph := speedHeap{}
heap.Init(&ph)
speedSum := 0
var max int64
for _, index := range indexes {
if ph.Len() == k {
speedSum -= heap.Pop(&ph).(int)
}
speedSum += speed[index]
heap.Push(&ph, speed[index])
max = Max(max, int64(speedSum)*int64(efficiency[index]))
}
return int(max % (1e9 + 7))
}

type speedHeap []int

func (h speedHeap) Less(i, j int) bool  { return h[i] < h[j] }
func (h speedHeap) Swap(i, j int)       { h[i], h[j] = h[j], h[i] }
func (h speedHeap) Len() int            { return len(h) }
func (h *speedHeap) Push(x interface{}) { *h = append(*h, x.(int)) }
func (h *speedHeap) Pop() interface{} {
res := (*h)[len(*h)-1]
*h = (*h)[:h.Len()-1]
return res
}

func Max(a, b int64) int64 {
if a > b {
return a
}
return b
}
`````` Sep 11, 2022 Edit this page