Leetcode 826. Most Profit Assigning Work
You have n jobs and m workers. You are given three input arrays difficulty, profit, and worker where:
difficulty[i] represents the difficulty of the i-th jobprofit[i] represents the profit of the i-th jobworker[j] represents the ability of the j-th worker (max difficulty the worker can do)Each worker can be assigned at most one job, but only if the job’s difficulty is at most the worker’s ability. Each worker wants to maximize their profit by doing a job with the highest profit for which they can handle the difficulty.
Return the maximum profit we can achieve.
difficulty, profit, and worker are all integer arrays where 1 <= difficulty.length == profit.length <= 10^4 and 1 <= worker.length <= 10^4.difficulty, profit, and worker constrained?
[1, 10^5].difficulty and profit arrays and sort the pairs by difficulty.maxProfit[i] stores the maximum profit achievable up to the i-th job when sorted by difficulty.worker array.maxProfit array to get the maximum profit for that difficulty.#include <vector>
#include <algorithm>
using namespace std;
int maxProfitAssignment(vector<int>& difficulty, vector<int>& profit, vector<int>& worker) {
int n = difficulty.size();
vector<pair<int, int>> jobs;
for (int i = 0; i < n; ++i) {
jobs.push_back({difficulty[i], profit[i]});
}
// Sort jobs by difficulty
sort(jobs.begin(), jobs.end());
// Prefix maximum profit array
vector<int> maxProfits(n);
maxProfits[0] = jobs[0].second;
for (int i = 1; i < n; ++i) {
maxProfits[i] = max(maxProfits[i - 1], jobs[i].second);
}
// Sort worker by their ability
sort(worker.begin(), worker.end());
int maxTotalProfit = 0;
int j = 0; // To track the current job index
for (int ability : worker) {
while (j < n && jobs[j].first <= ability) {
++j;
}
if (j > 0) {
maxTotalProfit += maxProfits[j - 1];
}
}
return maxTotalProfit;
}
jobs array takes O(n log n).maxProfits array takes O(n).worker array takes O(m log m).worker array and potentially scans all jobs, leading to O(n + m).Thus, the overall time complexity is: [ O(n \log n + m \log m + n + m) \approx O((n + m) \log (n + m)) ]
This is efficient for the given constraints.
Got blindsided by a question you didn’t expect?
Spend too much time studying?
Or simply don’t have the time to go over all 3000 questions?