Maximum Performance of a Team in C++


Suppose there are n engineers. They are numbered from 1 to n and we also have two arrays: speed and efficiency, here speed[i] and efficiency[i] represent the speed and efficiency for the ith engineer. We have to find the maximum performance of a team composed of at most k engineers. The answer may be very large so return it modulo 10^9 + 7.

Here the performance of a team is the sum of their engineers' speeds multiplied by the minimum efficiency among their engineers.

So, if the input is like n = 6, speed = [1,5,8,2,10,3], efficiency = [9,7,2,5,4,3], k = 2, then the output will be 60, as we have the maximum performance of the team by selecting engineer with speed 10 and efficiency 4 and engineer with speed 5 and efficiency 7. That is, performance = (10 + 5) * min(4, 7) = 60.

To solve this, we will follow these steps −

  • ret := 0

  • Define one 2D array v

  • for initialize i := 0, when i < n, update (increase i by 1), do −

    • insert { e[i], s[i] } at the end of v

  • sort the array v in reverse order

  • Define one priority queue pq

  • sum := 0

  • for initialize i := 0, when i < n, update (increase i by 1), do −

    • if size of pq is same as k, then −

      • sum := top element of sum - pq

      • delete element from pq

    • sum := sum + v[i, 1]

    • insert v[i, 1] into pq

    • ret := maximum of ret and sum * v[i, 0]

  • return ret mod (1^9 + 7)

Let us see the following implementation to get better understanding −

Example

 Live Demo

#include <bits/stdc++.h>
using namespace std;
class Solution {
   public:
   int maxPerformance(int n, vector<int>& s, vector<int>& e, int k){
      long long int ret = 0;
      vector<vector<int> > v;
      for (int i = 0; i < n; i++) {
         v.push_back({ e[i], s[i] });
      }
      sort(v.rbegin(), v.rend());
      priority_queue<int, vector<int>, greater<int> > pq;
      long long int sum = 0;
      for (int i = 0; i < n; i++) {
         if (pq.size() == k) {
            sum -= pq.top();
            pq.pop();
         }
         sum += v[i][1];
         pq.push(v[i][1]);
         ret = max(ret, sum * v[i][0]);
      }
      return ret % (long long int)(1e9 + 7);
   }
};
main(){
   Solution ob;
   vector<int> v = {1,5,8,2,10,3};
   vector<int> v1 = {9,7,2,5,4,3};
   cout << (ob.maxPerformance(6,v,v1,2));
}

Input

6, {1,5,8,2,10,3}, {9,7,2,5,4,3}, 2

Output

60

Updated on: 09-Jun-2020

184 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements