Most Profit Assigning Work

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

  • difficulty[i] and profit[i] are the difficulty and the profit of the ith job, and
  • worker[j] is the ability of jth worker (i.e., the jth 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.

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.

思路: 把job按照difficulty 从小到大排序,然后每个woker去扫,同时记录最大profit,最后相加;

O(n logn + m * n );

class Solution {
    class Node {
        public int difficulty;
        public int profit;
        public Node(int difficulty, int profit) {
            this.difficulty = difficulty;
            this.profit = profit;
        }
    }
    
    public int maxProfitAssignment(int[] difficulty, int[] profit, int[] worker) {
        int n = difficulty.length;
        Node[] nodes = new Node[n];
        for(int i = 0; i < difficulty.length; i++) {
            nodes[i] = new Node(difficulty[i], profit[i]);
        }
        
        Arrays.sort(nodes, (a, b) -> a.difficulty - b.difficulty);
        int res = 0;
        for(int i = 0; i < worker.length; i++) {
            int j = 0;
            int curmax = 0;
            while(j < nodes.length && nodes[j].difficulty <= worker[i]) {
                curmax = Math.max(curmax, nodes[j].profit);
                j++;
            }
            res += curmax;
        }
        return res;
    }
}

 

 思路2:用dp来pre compute,先bucket记录每个diffucuty能够达到的profit,然后记录一下到目前为止的最大profit,然后woker去取最大值,加起来就是答案;O(N)

class Solution {
    public int maxProfitAssignment(int[] difficulty, int[] profit, int[] worker) {
        int[] dp = new int[100001];
        for(int i = 0; i < difficulty.length; i++) {
            int index = difficulty[i];
            dp[index] = Math.max(dp[index], profit[i]); 
        }
        
        for(int i = 1; i < dp.length; i++) {
            dp[i] = Math.max(dp[i - 1], dp[i]);
        }
        
        int res = 0;
        for(int i = 0; i < worker.length; i++) {
            res += dp[worker[i]];
        }
        return res;
    }
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值