Most Profit Assigning Work in C++


Suppose we have jobs difficulty[i] and this array indicates the difficulty of the ith job, and profit[i] is the profit of the ith job. Now consider we have some workers. worker[i] is the ability of the ith worker, this means that this worker can only complete a job with difficulty at most worker[i]. Every worker can do at most one job, but one job can be completed multiple times. We have to find what is the most profit we can make?

For example, if the input is like difficulty = [2,4,6,8,10] and profit = [10,20,30,40,50] and worker = [4,5,6,7], then the output will be 100. So workers can be assigned job difficulty [4,4,6,6], and the gained profit [20,20,30,30], that is 100 in total.

To solve this, we will follow these steps −

  • ans := 0 and n := size of profit array
  • sort the worker array
  • make a list of pairs called v
  • for i in range 0 to n – 1,
    • insert pair (difficulty[i], profit[i]) into v
  • sort the v array
  • maxVal := 0, m := size of the worker array and j := 0
  • for i in range 0 to m – 1
    • while j < n and first value of v[j] <= worker[i]
      • maxVal := max of maxVal and second value of v[j]
      • increase j by 1
    • ans := ans + maxVal
  • return ans

Let us see the following implementation to get better understanding −

Example

 Live Demo

#include <bits/stdc++.h>
using namespace std;
class Solution {
   public:
   int maxProfitAssignment(vector<int>& difficulty, vector<int>& profit, vector<int>& worker) {
      int ans = 0;
      sort(worker.begin(), worker.end());
      vector < pair <int, int> > v;
      int n = profit.size(); // Number of jobs
      for(int i = 0; i < n; i++){
         v.push_back({difficulty[i], profit[i]});
      }
      sort(v.begin(), v.end());
      int maxVal = 0;
      int m = worker.size(); // Number of workers
      int j = 0;
      for(int i = 0; i < m; i++){
         while(j < n && v[j].first <= worker[i]){
            maxVal = max(maxVal, v[j].second);
            j++;
         }
         ans += maxVal;
      }
      return ans;
   }
};
int main() {
   Solution ob1;
   vector<int> difficulty{2,4,6,8,10};
   vector<int> profit{10,20,30,40,50};
   vector<int> worker{4,5,6,7};
   cout << ob1.maxProfitAssignment(difficulty, profit, worker) << endl;
   return 0;
}

Input

[2,4,6,8,10]
[10,20,30,40,50]
[4,5,6,7]
vector<int> difficulty{2,4,6,8,10};
vector<int> profit{10,20,30,40,50};
vector<int> worker{4,5,6,7};

Output

100

Updated on: 30-Apr-2020

249 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements