← Home

1383. Maximum Performance of a Team

LeetCode article · C++ solution
Website made by wuisabel-gif · Original C++ code by keineahnung2345
heap / priority queueC++Markdown
138

The trick here is to name the state correctly, then let the implementation follow. For 1383. Maximum Performance of a Team, the solution in this repository is mainly a heap / priority queue solution.

Guide

What?

Before optimizing anything, pin down what information is still useful after each move. Instead of trying to be clever immediately, read the code as a sequence of questions:

  • What state are we keeping?
  • How do we move from one state to the next?
  • When do we know the answer is already determined?

For this file, the main tools are: heap / priority queue, backtracking, greedy.

The notes already sitting in the source point us in the right direction:

  • TLE
  • 23 / 53 test cases passed.

Guide

When?

Use this approach when the hard part is not syntax, but deciding what must stay true after every update. The accepted code reduces that pressure by storing exactly the information that remains useful later.

The important function names to track are backtrack, maxPerformance, ids.

Guide

Why?

The point of the implementation is not to make the code longer. It is to avoid doing the same thinking twice.

  • Sorting is used to make local choices comparable, so the later scan does not have to rediscover order.
  • The heap keeps the best candidate available without sorting the whole world every time.
  • The final return is not magic; it is the invariant after the loops or recursion have finished doing their accounting.

Guide

How?

Walk through the solution in this order:

  1. Read the setup variables first.
  2. Follow the main loop or recursive helper next.
  3. Watch where invalid states get skipped.
  4. Check which value survives to the return statement.

The most important competitive-programming habit here is to trust the invariant. Once the invariant is right, the loops become much less scary.

Guide

Complexity

  • Time: O(n) to O(n log n), depending on the dominant loop or data structure operation
  • Space: O(n) in the usual case for auxiliary containers or recursion

Guide

C++ Solution

Your submission

The accepted solution

solution.cpp
01//TLE
02//23 / 53 test cases passed.
03class Solution {
04public:
05    int ans;
06    int n, k;
07    vector<int> speed, efficiency;
08    long mod = 1e9 + 7;
09    
10    void backtrack(vector<int>& ids, vector<int>& combIds, int start){
11        if(combIds.size() == k){
12            long perf = 0;
13            int eff = INT_MAX;
14            int speedSum = 0;
15            for(int combId : combIds){
16                eff = min(efficiency[combId], eff);
17                speedSum += speed[combId];
18            }
19            perf = ((eff % mod) * (speedSum % mod)) % mod;
20            // if((int)perf > ans){
21            //     for(int i = 0; i < k; i++){
22            //         cout << combIds[i] << " ";
23            //     }
24            //     cout << endl;
25            // }
26            ans = max((int)perf, ans);
27        }else{
28            for(int i = start; i < n; i++){
29                combIds.push_back(i);
30                backtrack(ids, combIds, i+1);
31                combIds.pop_back();
32            }
33        }
34    }
35    
36    int maxPerformance(int n, vector<int>& speed, vector<int>& efficiency, int k) {
37        ans = 0;
38        this->n = n;
39        this->speed = speed;
40        this->efficiency = efficiency;
41        //we can have 1 to k engineers!
42        //not necessary k!
43        vector<int> combIds;
44        
45        vector<int> ids(n);
46        iota(ids.begin(), ids.end(), 0);
47        
48        for(int i = 1; i <= k; i++){
49            this->k = i;
50            backtrack(ids, combIds, 0);
51        }
52        
53        // cout << endl;
54        return ans;
55    }
56};
57
58//https://leetcode.com/problems/maximum-performance-of-a-team/discuss/539687/Python-Priority-Queue
59//Solution 2: Priority Queue
60//Runtime: 124 ms, faster than 33.33% of C++ online submissions for Maximum Performance of a Team.
61//Memory Usage: 18.2 MB, less than 100.00% of C++ online submissions for Maximum Performance of a Team.
62//time: O(nlogk), space: O(k)
63class Solution {
64public:
65    int maxPerformance(int n, vector<int>& speed, vector<int>& efficiency, int k) {
66        vector<pair<int, int>> ess;
67        for (int i = 0; i < n; i++){
68            ess.push_back({efficiency[i], speed[i]});
69        }
70        //sort by efficiency and then by speed, descending
71        sort(ess.rbegin(), ess.rend());
72
73        long sumS = 0, res = 0;
74        priority_queue <int, vector<int>, greater<int> > pq;
75        //itereate through efficiency
76        for (int i = 0; i < n; i++) {
77            //for each efficiency, find the maximum possible combination(of size <= k) of speed
78            //possible speeds are the speed whose efficiency >= current efficiency
79            pq.push(ess[i].second);
80            //sumS: the sum of the combination of speed for current efficiency
81            sumS += ess[i].second;
82            // cout << "push " << ess[i].second << ", sumS: " << sumS << endl;
83            if (pq.size() > k) {
84                sumS -= pq.top();
85                // cout << "pop " << pq.top() << ", sumS: " << sumS << endl;
86                pq.pop();
87            }
88            // cout << "current res: " << sumS * ess[i].first << endl;
89            res = max(res, sumS * ess[i].first);
90        }
91        return res % (int)(1e9+7);
92    }
93};
94
95//Solution 1: Binary Insert
96//TLE
97//52 / 53 test cases passed.
98//time: O(N^2), space: O(N)
99class Solution {
100public:
101    int maxPerformance(int n, vector<int>& speed, vector<int>& efficiency, int k) {
102        vector<pair<int, int>> ess;
103        for(int i = 0; i < n; i++){
104            ess.emplace_back(efficiency[i], speed[i]);
105        }
106        //descending
107        sort(ess.rbegin(), ess.rend());
108        
109        //sorted array of speeds, descending
110        vector<int> speedComb;
111        
112        long sSum = 0, res = 0;
113        
114        for(int i = 0; i < n; i++){
115            //use insertion sort
116            vector<int>::iterator it = find_if(speedComb.begin(), speedComb.end(), 
117                [&ess, &i](int e){return e < ess[i].second;});
118            speedComb.insert(it, ess[i].second);
119            sSum += ess[i].second;
120            if(speedComb.size() > k){
121                sSum -= speedComb[speedComb.size()-1];
122                speedComb.pop_back();
123            }
124            res = max(res, sSum * ess[i].first);
125        }
126        
127        return res % (int)(1e9+7);
128    }
129};

Cost

Complexity

Time
O(n) to O(n log n), depending on the dominant loop or data structure operation
Dominated by the main traversal, recursion, or data-structure operations in the code.
Space
O(n) in the usual case for auxiliary containers or recursion
Auxiliary state plus the answer structure where the problem requires one.