Taro Logo

Minimum Cost to Hire K Workers

#1 Most AskedHard
2 views
Topics:
ArraysGreedy AlgorithmsHeap (Priority Queue)

There are n workers. You are given two integer arrays quality and wage where quality[i] is the quality of the ith worker and wage[i] is the minimum wage expectation for the ith worker.

We want to hire exactly k workers to form a paid group. To hire a group of k workers, we must pay them according to the following rules:

  1. Every worker in the paid group must be paid at least their minimum wage expectation.
  2. In the group, each worker's pay must be directly proportional to their quality. This means if a worker’s quality is double that of another worker in the group, then they must be paid twice as much as the other worker.

Given the integer k, return the least amount of money needed to form a paid group satisfying the above conditions. Answers within 10-5 of the actual answer will be accepted.

Example 1:

Input: quality = [10,20,5], wage = [70,50,30], k = 2
Output: 105.00000
Explanation: We pay 70 to 0th worker and 35 to 2nd worker.

Example 2:

Input: quality = [3,1,10,10,1], wage = [4,8,2,2,7], k = 3
Output: 30.66667
Explanation: We pay 4 to 0th worker, 13.33333 to 2nd and 3rd workers separately.

Constraints:

  • n == quality.length == wage.length
  • 1 <= k <= n <= 104
  • 1 <= quality[i], wage[i] <= 104

Solution


Clarifying Questions

When you get asked this question in a real-life environment, it will often be ambiguous (especially at FAANG). Make sure to ask these questions in that case:

  1. What are the constraints on the lengths of the `quality` and `wage` arrays, and what is the range of values for individual qualities and wages?
  2. Is it guaranteed that we can always successfully form a paid group of exactly `K` workers, or should we handle cases where it's impossible (e.g., returning `-1` or throwing an exception)?
  3. Can the `quality` or `wage` arrays contain duplicate worker profiles, and how should workers with identical wage-to-quality ratios be handled?
  4. What data type should be used for the final return value to prevent potential precision issues or integer overflow when calculating proportional wages?
  5. Can `K` be greater than the total number of workers available in the input arrays?

Brute Force Solution

Approach

To solve this problem using the brute force approach, we want to try every possible combination of workers to see which group gives us the cheapest valid total pay. We will test every group of the required size, check if they meet all the pay and quality rules, and keep track of the lowest total cost we find.

Here's how the algorithm would work step-by-step:

  1. Gather all the available workers, each with their own minimum pay requirement and work quality.
  2. Generate every single possible group of workers that contains the exact required number of people.
  3. For each of these groups, figure out which worker's relative salary expectation sets the baseline pay rate for the whole group.
  4. Calculate how much each worker in the group would need to be paid based on that highest baseline rate.
  5. Check if every worker in the group is getting at least their minimum required pay.
  6. If anyone in the group is getting less than they demand, throw this group away because it violates the rules.
  7. If the group is valid, add up everyone's pay to find the total cost for this specific combination.
  8. Keep a running note of the lowest total cost seen so far, and update it whenever you find a valid group that is cheaper.
  9. Once you have checked every single possible group combination, the lowest cost you recorded is your final answer.

Code Implementation

import itertools


def mincost_to_hire_workers(quality_list, wage_list, worker_target_count):
    total_worker_count = len(quality_list)
    minimum_total_cost = float('inf')

    # We generate every combination of worker indices to evaluate all possible groups
    for worker_combination in itertools.combinations(range(total_worker_count), worker_target_count):
        group_ratios = []

        for worker_index in worker_combination:
            wage_to_quality_ratio = wage_list[worker_index] / quality_list[worker_index]
            group_ratios.append(wage_to_quality_ratio)

        maximum_ratio = max(group_ratios)
        current_group_cost = 0
        is_group_valid = True

        for worker_index in worker_combination:
            required_payment = quality_list[worker_index] * maximum_ratio

            if required_payment < wage_list[worker_index]:
                is_group_valid = False
                break

            current_group_cost += required_payment

        # We only consider valid groups that meet minimum wage demands for everyone
        if is_group_valid:
            if current_group_cost < minimum_total_cost:
                minimum_total_cost = current_group_cost

    # We ensure we return zero if no valid combinations were ever found
    if minimum_total_cost == float('inf'):
        return 0.0

    return minimum_total_cost

Big(O) Analysis

Time Complexity
O(C(n, k) * k) – Generating every possible combination of K workers from a total of n workers results in C(n, k) groups. For each of these generated combinations, we iterate through k workers to validate their pay rates and sum their total costs. This leads to approximately C(n, k) * k operations, where C(n, k) is the binomial coefficient representing combinations of n taken k at a time. Therefore, the overall time complexity is O(C(n, k) * k).
Space Complexity
O(K) – The algorithm requires auxiliary space to keep track of the current combination of K workers being evaluated. Specifically, storing the selected group of size K, along with a few scalar variables for running costs and baseline ratios, utilizes memory proportional to K. Since K is at most the total number of workers N, the extra memory required is bounded by K elements at any single time. Therefore, simplifying this memory usage to Big O notation yields O(K).

Optimal Solution

Approach

To find the cheapest group of workers, we realize that every worker has a specific ratio of wage to quality that sets the baseline pay scale for the whole team. By organizing the workers by this ratio and using a clever tracking tool, we can efficiently test every possible team leader and find the absolute minimum total payment.

Here's how the algorithm would work step-by-step:

  1. Calculate the wage-to-quality ratio for every single person so we know how expensive each person is relative to their output.
  2. Sort all the workers from the cheapest ratio to the most expensive ratio to create a logical order of consideration.
  3. Imagine walking down this sorted line and treating each person as the anchor who sets the minimum pay standard for everyone on their team.
  4. Keep track of the quality scores of the people chosen so far, always holding onto the ones with the lowest quality scores to keep total costs down.
  5. Whenever you have gathered enough people to form a full team, calculate the total cost by multiplying the team size and quality sum by the current anchor person's ratio.
  6. Compare this total cost against the lowest cost found so far and keep the smaller number.
  7. Continue down the line until every valid team possibility has been considered, ensuring you never miss the absolute cheapest combination.

Code Implementation

import heapq


def min_cost_to_hire_workers(quality_list, wage_list, worker_target_count):
    worker_collection = []
    for worker_quality, worker_wage in zip(quality_list, wage_list):
        ratio_value = worker_wage / worker_quality
        worker_collection.append((ratio_value, worker_quality))

    # Sorting by ratio allows each worker to act as a fair wage baseline for cheaper peers.
    worker_collection.sort(key=lambda item: item[0])

    minimum_total_cost = float('inf')
    current_quality_sum = 0
    highest_quality_heap = []

    for wage_ratio, worker_quality in worker_collection:
        heapq.heappush(highest_quality_heap, -worker_quality)
        current_quality_sum += worker_quality

        # Drop the highest quality worker to minimize the sum once team size exceeds the limit.
        if len(highest_quality_heap) > worker_target_count:
            current_quality_sum += heapq.heappop(highest_quality_heap)

        # Calculate cost only when a full team of required size is successfully gathered.
        if len(highest_quality_heap) == worker_target_count:
            potential_total_cost = current_quality_sum * wage_ratio
            minimum_total_cost = min(minimum_total_cost, potential_total_cost)

    return minimum_total_cost

Big(O) Analysis

Time Complexity
O(n log n) – Calculating the wage-to-quality ratio and sorting all n workers by this ratio takes O(n log n) time. As we iterate through the sorted workers, we maintain a max-heap of size k to track the lowest quality scores, where each heap insertion or deletion takes O(log k) time. Since we perform this heap operation for all n workers, the overall time complexity is dominated by the sorting and heap operations, leading to n log k operations that approximate to O(n log n).
Space Complexity
O(k) – We maintain a max-heap priority queue to track the quality scores of the workers chosen so far, which requires auxiliary space proportional to the team size K. As we iterate through all N workers, we store worker objects containing their wage and quality in a temporary list or array of size N for sorting. The dominant auxiliary data structures are the sorting storage of size N and the priority queue of size K, which simplifies to O(N) auxiliary space overall, or O(K) if the sorting is done in place with an external array reference.

Edge Cases

K equals 1
How to Handle:
The algorithm correctly calculates the minimum wage-to-quality ratio times that worker's quality, which simplifies to their exact minimum wage.
K equals the total number of workers
How to Handle:
The max heap will process all workers and correctly compute the sum of all qualities multiplied by the maximum ratio in the group.
Duplicate ratios among workers
How to Handle:
Sorting by ratio handles identical ratios stably, and the greedy heap selection naturally picks the subset with the smallest qualities.
Extremely large quality and wage values causing integer overflow
How to Handle:
We must use 64-bit integer types for accumulating total cost and quality sum to prevent arithmetic overflow during intermediate calculations.
Floating point precision issues with wage-to-quality ratios
How to Handle:
Using standard double precision for ratios is sufficient since workers are sorted by ratio and compared relative to each other.
Zero or negative values in quality or wage arrays
How to Handle:
Problem constraints specify positive integers, so zero or negative inputs are invalid and assumed not to occur.
Maximum-sized inputs up to 10,000 workers
How to Handle:
An O(N log N) sorting and priority queue approach efficiently processes the upper constraints well within time limits.
0/8 completed