小鱼刷leetcode---826. 安排工作以达到最大收益

56 阅读2分钟

开启掘金成长之旅!这是我参与「掘金日新计划 · 12 月更文挑战」的第29天,点击查看活动详情

一 描述

826. 安排工作以达到最大收益 - 力扣(LeetCode)get-indices-after-sorting-array/)

你有 n 个工作和 m 个工人。给定三个数组: difficultyprofit 和 worker ,其中:

  • difficulty[i] 表示第 i 个工作的难度,profit[i] 表示第 i 个工作的收益。

  • worker[i] 是第 i 个工人的能力,即该工人只能完成难度小于等于 worker[i] 的工作。 每个工人 最多 只能安排 一个 工作,但是一个工作可以 完成多次

  • 举个例子,如果 3 个工人都尝试完成一份报酬为 $1 的同样工作,那么总收益为 $3 。如果一个工人不能完成任何工作,他的收益为 $0 。 返回 在把工人分配到工作岗位后,我们所能获得的最大利润 。

 

示例 1:

输入: difficulty = [2,4,6,8,10], profit = [10,20,30,40,50], worker = [4,5,6,7]
输出: 100 
解释: 工人被分配的工作难度是 [4,4,6,6] ,分别获得 [20,20,30,30] 的收益。

示例 2:

输入: difficulty = [85,47,57], profit = [24,66,99], worker = [40,25,25]
输出: 0

提示:

  • n == difficulty.length
  • n == profit.length
  • m == worker.length
  • 1 <= n, m <= 104
  • 1 <= difficulty[i], profit[i], worker[i] <= 10^5

二 分析

此题需要分析难度、收益和能力三者之间的关系,

采取下面两个思路:

第一:需要对收益排序,因为每个人都是想收益最大,并且可以重复。

第二:根据工人的能力和难度进行比较,遍历收益数组,看哪个难度可以满足,第一个满足的必然是收益最大的!

这里不能忽略一个点就是:需要建立收益和难度的关联关系,这样排序就好比较了!

三 答案

struct maxHash {
    int diff;
    int profit;
};

int cmp(struct maxHash* a, struct maxHash* b) {
    return b->profit - a->profit; //降序排序
}

int everyWork(struct maxHash *hash, int difficulty, int cap) {
    for (int j = 0; j < difficulty; j++) {
        if (hash[j].diff <= cap) {
            return hash[j].profit;
		}
	}
    return 0;
}

int maxProfitAssignment(int* difficulty, int difficultySize, int* profit, int profitSize, int* worker, int workerSize) {
    if (difficulty == NULL || profit == NULL || worker == NULL) {
       return -1;
	}
	int sum = 0;
    struct maxHash *max = (struct maxHash *)malloc(sizeof(struct maxHash) * difficultySize);
	if (max == NULL) {
       return -1;
	}
    memset(max, 0, sizeof(struct maxHash) * difficultySize);
	for (int i = 0; i < difficultySize; i++) {
        max[i].diff = difficulty[i];
		max[i].profit = profit[i];
	}
    // 收益从大到小排序
    printf("max[0]= %d\n", max[0]);
	(void)qsort(max, difficultySize, sizeof(max[0]), cmp);
	for (int i = 0; i < difficultySize; i++) {
       printf("i=%d diff=%d profit=%d\n",i,max[i].diff,max[i].profit);
	}
    for (int j = 0; j < workerSize; j++) {
	    sum += everyWork(max, difficultySize, worker[j]);
    }
    return sum;
}