|
| 1 | +/** |
| 2 | + * 826. Most Profit Assigning Work |
| 3 | + * https://leetcode.com/problems/most-profit-assigning-work/ |
| 4 | + * Difficulty: Medium |
| 5 | + * |
| 6 | + * You have n jobs and m workers. You are given three arrays: difficulty, profit, and worker where: |
| 7 | + * - difficulty[i] and profit[i] are the difficulty and the profit of the ith job, and |
| 8 | + * - worker[j] is the ability of jth worker (i.e., the jth worker can only complete a job with |
| 9 | + * difficulty at most worker[j]). |
| 10 | + * |
| 11 | + * Every worker can be assigned at most one job, but one job can be completed multiple times. |
| 12 | + * - For example, if three workers attempt the same job that pays $1, then the total profit will |
| 13 | + * be $3. If a worker cannot complete any job, their profit is $0. |
| 14 | + * |
| 15 | + * Return the maximum profit we can achieve after assigning the workers to the jobs. |
| 16 | + */ |
| 17 | + |
| 18 | +/** |
| 19 | + * @param {number[]} difficulty |
| 20 | + * @param {number[]} profit |
| 21 | + * @param {number[]} worker |
| 22 | + * @return {number} |
| 23 | + */ |
| 24 | +var maxProfitAssignment = function(difficulty, profit, worker) { |
| 25 | + const jobs = difficulty.map((d, i) => [d, profit[i]]); |
| 26 | + jobs.sort((a, b) => a[0] - b[0]); |
| 27 | + |
| 28 | + const n = jobs.length; |
| 29 | + const bestProfit = new Array(n); |
| 30 | + let maxProfit = 0; |
| 31 | + |
| 32 | + for (let i = 0; i < n; i++) { |
| 33 | + maxProfit = Math.max(maxProfit, jobs[i][1]); |
| 34 | + bestProfit[i] = [jobs[i][0], maxProfit]; |
| 35 | + } |
| 36 | + |
| 37 | + return worker.reduce((total, ability) => { |
| 38 | + let left = 0; |
| 39 | + let right = n - 1; |
| 40 | + |
| 41 | + while (left <= right) { |
| 42 | + const mid = (left + right) >> 1; |
| 43 | + bestProfit[mid][0] <= ability ? left = mid + 1 : right = mid - 1; |
| 44 | + } |
| 45 | + |
| 46 | + return total + (right >= 0 ? bestProfit[right][1] : 0); |
| 47 | + }, 0); |
| 48 | +}; |
0 commit comments