You are given two integer arrays difficulty and profit where difficulty[i] and profit[i] indicate the difficulty and profit of the iᵗʰ job, and an integer array worker where worker[j] is the skill level of the jᵗʰ worker.
Return the maximum profit we can achieve, given that each worker can be assigned at most one job and the job assigned to the worker has a difficulty less than or equal to the worker’s skill level.
To solve this problem optimally, we can:
difficulty and profit into a list of tuples and sort them based on difficulty. This allows easier assignment of maximum profitable jobs to workers.We will iterate through the workers in ascending order of their skills, maintaining the maximum profit seen so far from the available jobs they can perform.
jobs and workers both takes (O(n \log n + m \log m)), where (n) is the number of jobs and (m) is the number of workers.Thus, the overall time complexity is (O(n \log n + m \log m)).
def maxProfitAssignment(difficulty, profit, worker):
# Combine difficulty and profit into a list of tuples
jobs = sorted(zip(difficulty, profit))
# Sort the worker array
worker.sort()
max_profit = 0
max_assignable_profit = 0
job_index = 0
n = len(jobs)
for w in worker:
# Update the max profit for all jobs that this worker can do
while job_index < n and jobs[job_index][0] <= w:
max_assignable_profit = max(max_assignable_profit, jobs[job_index][1])
job_index += 1
# Add the best profit that this worker can achieve
max_profit += max_assignable_profit
return max_profit
# Example usage
difficulty = [2, 4, 6, 8, 10]
profit = [10, 20, 30, 40, 50]
worker = [4, 5, 6, 7]
print(maxProfitAssignment(difficulty, profit, worker)) # Output: 100
difficulty and profit into jobs: We zip and sort them.worker array: To ensure we are processing the least skilled workers first.max_profit to store total profit.max_assignable_profit to store the best profit for the current worker’s skill.max_assignable_profit to be the maximum profit they can achieve.This solution ensures each worker is assigned the best job they can do with a time complexity of (O(n \log n + m \log m)).
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?