DSA problem
Most Profit Assigning Work
You have n jobs and m workers. You are given three arrays: difficulty, profit, and worker where difficulty[i] and profit[i] are the difficulty and the profit of the i-th job, and worker[j] is the ability of j-th worker (i.e., the j-th worker can only complete a job with difficulty at most worker[j]). Every worker can be assigned at most one job, but one job can be completed multiple times. For example, if three workers attempt the same job that pays 1$, then the total profit will be 3$. If a worker cannot complete any job, their profit is 0$. Return the maximum profit we can achieve after assigning the workers to the jobs.
A brute-force pairing tries every (worker, job) combination at cost O(n * m) per query — workable for tiny inputs but quickly stops scaling. We can do much better by recognizing that for each worker, the best job is the highest-profit one whose difficulty is within reach. If we can answer "max profit among all jobs with difficulty <= D" quickly, every worker just looks up their own D.
Sorting unlocks the classic two-pointer pattern. Sort jobs by ascending difficulty and workers by ascending ability. Maintain a job pointer j and a running bestProfit. For each worker in ascending order of ability, advance j while difficulty[j] <= worker.ability, updating bestProfit = max(bestProfit, profit[j]). The current worker contributes bestProfit to the total.
The key correctness observation is monotonicity: as worker ability increases, the set of doable jobs only grows, so bestProfit never decreases. This lets us reuse the same bestProfit across the entire workers loop without resetting. Total time O((n + m) log(n + m)) dominated by the two sorts, and O(n) extra space for the sorted jobs.
Examples
difficulty = [2,4,6,8,10], profit = [10,20,30,40,50], worker = [4,5,6,7]100difficulty = [85,47,57], profit = [24,66,99], worker = [40,25,25]0difficulty = [13,37,58], profit = [4,90,96], worker = [34,73,45]190Constraints
- n == difficulty.length == profit.length
- m == worker.length
- 1 <= n, m <= 10^4
- 1 <= difficulty[i], profit[i], worker[i] <= 10^5
3 hints and a full solution walkthrough with step-by-step visualizations are available in the practice editor.