力扣貪心 1383. 最大的團隊表現值

公司有編號爲 1 到 n 的 n 個工程師,給你兩個數組 speed 和 efficiency ,其中 speed[i] 和 efficiency[i] 分別代表第 i 位工程師的速度和效率。請你返回由最多 k 個工程師組成的 ​​​​​​最大團隊表現值 ,由於答案可能很大,請你返回結果對 10^9 + 7 取餘後的結果。

團隊表現值 的定義爲:一個團隊中「所有工程師速度的和」乘以他們「效率值中的最小值」。

 

示例 1:

輸入:n = 6, speed = [2,10,3,1,5,8], efficiency = [5,4,3,9,7,2], k = 2
輸出:60
解釋:
我們選擇工程師 2(speed=10 且 efficiency=4)和工程師 5(speed=5 且 efficiency=7)。他們的團隊表現值爲 performance = (10 + 5) * min(4, 7) = 60 。
示例 2:

輸入:n = 6, speed = [2,10,3,1,5,8], efficiency = [5,4,3,9,7,2], k = 3
輸出:68
解釋:
此示例與第一個示例相同,除了 k = 3 。我們可以選擇工程師 1 ,工程師 2 和工程師 5 得到最大的團隊表現值。表現值爲 performance = (2 + 10 + 5) * min(5, 4, 7) = 68 。
示例 3:

輸入:n = 6, speed = [2,10,3,1,5,8], efficiency = [5,4,3,9,7,2], k = 4
輸出:72
 

提示:

1 <= n <= 10^5
speed.length == n
efficiency.length == n
1 <= speed[i] <= 10^5
1 <= efficiency[i] <= 10^8
1 <= k <= n

來源:力扣(LeetCode)
鏈接:https://leetcode-cn.com/problems/maximum-performance-of-a-team

兩個變量,枚舉效率(因爲速度是求和維護簡單)

先對效率排序

然後使用優先隊列進行維護:因爲枚舉了效率所以選k-1個最大的和(優先隊列維護),隊列中不夠k-1個則全加入不拋出
 

class Solution {
    public int maxPerformance(int n, int[] speed, int[] efficiency, int k) {
        int[][] items = new int[n][2];
        for(int i = 0 ; i < n ; i++){
            items[i][0] = speed[i];
            items[i][1] = efficiency[i];
        }
        Arrays.sort(items,(a, b) -> b[1] - a[1]);
        // Arrays.sort(items, new Comparator<int[]>(){
        //    @Override
        //     public int compare(int[] a, int[] b){
        //         return b[1] - a[1];
        //     }
        // });
        PriorityQueue<Integer> queue = new PriorityQueue<>();
        long res = 0, sum = 0;
        for(int i = 0 ; i < n ; i++){
            if(queue.size() > k - 1){
                sum -= queue.poll();
            }
            res = Math.max(res, (sum + items[i][0])* items[i][1]);
            queue.add(items[i][0]);
            sum += items[i][0];
        }
        return (int)(res % ((int)1e9 + 7));
    }
}

相似題目

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章