Sponsored
Sponsored
In this approach, we sort both jobs by difficulty and workers by their ability. We then iterate over each worker and find the highest profit job they can perform using a greedy approach.
First, we pair each job's difficulty with its profit and then sort these pairs by difficulty. We also sort the worker array. Next, for each worker, we iterate through the sorted job list and keep track of the maximum profit the worker can obtain, given that their ability must be greater than or equal to the job's difficulty. This ensures that each worker is assigned the most profitable job they can perform, thus maximizing the total profit.
Time Complexity: O(n log n + m log m)
Space Complexity: O(n)
1#include <iostream>
2#include <vector>
3#include <algorithm>
4
5using namespace std;
6
7int maxProfitAssignment(vector<int>& difficulty, vector<int>& profit, vector<int>& worker) {
8 vector<pair<int, int>> jobs;
9 for (size_t i = 0; i < difficulty.size(); ++i) {
10 jobs.emplace_back(difficulty[i], profit[i]);
11 }
12 sort(jobs.begin(), jobs.end());
13 sort(worker.begin(), worker.end());
14
15 int maxProfit = 0, best = 0, j = 0;
16 for (auto& ability : worker) {
17 while (j < jobs.size() && ability >= jobs[j].first) {
18 best = max(best, jobs[j].second);
19 ++j;
20 }
21 maxProfit += best;
22 }
23 return maxProfit;
24}
25
26int main() {
27 vector<int> difficulty = {2, 4, 6, 8, 10};
28 vector<int> profit = {10, 20, 30, 40, 50};
29 vector<int> worker = {4, 5, 6, 7};
30 int maxProfit = maxProfitAssignment(difficulty, profit, worker);
31 cout << "Max Profit: " << maxProfit << endl;
32 return 0;
33}
This C++ solution uses the pair and vector from STL to store jobs' difficulty and profit. Jobs and workers are sorted, then for each worker, it finds the most profitable job they can do using linear search and updates the maximum profit correspondingly.
This approach improves efficiency by preparing the job list in advance for profit maximization, and processes each worker in one pass. The basic idea is to preprocess the jobs to track the maximum profit obtainable up to each difficulty level. We create a running maximum profit and apply this to each worker based on their ability directly.
First, jobs are paired and sorted by difficulty; then, as we iterate through them, we constantly update the maximum profit obtainable up to each job's difficulty. When assessing workers, we simply apply their ability to this precomputed list to find the applicable maximum profit, ensuring minimal lookups and passing through the sorted jobs just once.
Time Complexity: O(n log n + m log m)
Space Complexity: O(n)
This C implementation sorts jobs and workers, and computes a running maximum profit for each difficulty level. The logic uses these precomputed profits to quickly sum the maximum applicable profits for each worker in a single iteration.