The Indian Engineer

Problem 826 Most Profit Assigning Work

Posted on Last edited 3 mins

Sorting Heap Max-Heap Greedy

Problem Statement

Link - Problem 826

Question

You have n jobs and m workers. You are given three arrays: difficulty, profit, and worker where:

Example 1

Input: difficulty = [2,4,6,8,10],
profit = [10,20,30,40,50],
worker = [4,5,6,7]
Output: 100
Explanation: Workers are assigned jobs of difficulty [4,4,6,6] and
 they get a profit of [20,20,30,30] separately.

Example 2

Input: difficulty = [85,47,57],
profit = [24,66,99],
worker = [40,25,25]
Output: 0

Constraints

Solution

class Solution {
public:
    int maxProfitAssignment(vector<int>& difficulty, vector<int>& profit, vector<int>& worker) {
        std::ios::sync_with_stdio(false);
        cin.tie(nullptr);
        cout.tie(nullptr);
        vector<pair<int,int>>pq(profit.size());

        for (int i = 0; i < profit.size(); i++)
        {
            pq[i]= {profit[i], difficulty[i]} ;
        }

        int wsize = worker.size(), pqsize = pq.size(),i =0, j=0, ans = 0;

        sort(worker.begin(), worker.end(), greater<int>());
        sort(pq.begin(),pq.end(),greater<pair<int,int>>());

        while (i < wsize && j < pqsize)
        {

            while(j<pqsize && pq[j].second>worker[i])
                j++;

            if(i == wsize || j == pqsize)
                break;

            while(i<wsize && j<pqsize && pq[j].second <= worker[i])
            {
                // cout<<j<<ans<<" "<<pq[j].first<<endl;
                ans+=pq[j].first;
                i++;
            }
        }
        return ans;
    }
};

Complexity Analysis

Explanation

1. Intuition

2. Implementation

Note - The code can be optimized by using a priority queue instead of sorting the pairs. Also this problem can be solved using a greedy approach as shown.