Minimum Cost to Hire K Workers

Hire exactly k workers, paid in proportion to their quality and never below their minimum wage, for the least total pay.

There are n workers. Worker i has a quality, quality[i], and a minimum wage, wage[i]. Hire exactly k of them as a team, paying each worker under two rules:

Return the least total pay for such a team.

Example 1
Input: quality = [10, 20, 5], wage = [70, 50, 30], k = 2
Output: 105.00000
Explanation: hire workers 0 and 2, paying 70 and 35.
Example 2
Input: quality = [3, 1, 10, 10, 1], wage = [4, 8, 2, 2, 7], k = 3
Output: 30.66667
Explanation: hire workers 0, 2 and 3, paying 4, 13.33333 and 13.33333.
Solution

The Idea

Think of hiring a small team where pay follows skill, and nobody accepts less than their asking wage. In Example 1, worker 0 has quality 10 and asks for at least 70. Worker 1 has quality 20 and asks for 50. Worker 2 has quality 5 and asks for 30.

Try workers 0 and 2. Because pay is proportional to quality, both are paid the same amount for each unit of quality. Call that amount the rate. Worker 0 needs 70 for 10 units, so the rate must be at least 7. Worker 2 needs 30 for 5 units, so 6 would do. A rate of 7 satisfies both: worker 0 gets 70, worker 2 gets 7 × 5 = 35, and the team costs 105.

So every worker has a lowest rate they accept, their wage divided by their quality: 7 for worker 0, 2.5 for worker 1 and 6 for worker 2. A team must use the largest of its members' lowest rates, and it costs that rate times the sum of its qualities. Hiring the two workers with the smallest wages, workers 1 and 2, costs 6 × (20 + 5) = 150. Worker 1's large quality is now paid at worker 2's rate.

With three workers there are only three teams of two to try. With hundreds of workers the teams are far too many. Which teams are worth looking at?

Turn the question around and first choose the worker who sets the rate. Sort the workers by their lowest rate. If worker 0 sets the rate of 7, every worker before it in that order accepts 7 too, so any of them can join. With the rate fixed, the cheapest team is the one with the smallest qualities. Look at the picture below.

Example 1 sorted by pay per unit of quality: worker 1 (2.5, quality 20), worker 2 (6, quality 5), worker 0 (7, quality 10). With the rate set by worker 2, the team is qualities 20 and 5 and costs 6 × 25 = 150. With the rate set by worker 0, the two smallest qualities are 5 and 10, and the team costs 7 × 15 = 105.

The top row holds the three workers in order of pay per unit. In the row labelled "rate set by worker 2: 6 per unit", only workers 1 and 2 accept the rate, so the team is qualities 20 and 5, and it costs 150. In the highlighted row, worker 0 raises the rate to 7, but now quality 20 can be left out. The team of qualities 5 and 10 costs 7 × 15 = 105, the answer. The bottom line covers worker 1: nobody else accepts 2.5, so there is no team of two at that rate.

So the plan is to walk through the workers in order of their rate. At each worker, take the k smallest qualities among that worker and the ones before, multiply their sum by the worker's rate, and keep the smallest cost seen.

Solution Approach

Trying every team is the simple way, and it is too slow. The faster way settles three things: the order to visit the workers in, how to keep the k smallest qualities as workers arrive, and what to do when the newest worker does not make it into those k.

Trying every team

Why not price every possible team? For Example 2, five workers and teams of three, there are just 10 teams. For 1,000 workers and teams of 500, the count is a number with 300 digits. Each team is easy to price, but there are far too many to visit.

Visiting workers in order of their rate

How do we know who may join? Sort the workers by wage divided by quality, smallest first. When the walk reaches a worker, everyone already passed has a rate no larger, so all of them accept this worker's rate. Equal rates do no harm: either worker can set the rate.

Keeping the k smallest qualities

Each new worker adds one quality to the pool. If the team now has one worker too many, which one should leave? The one with the largest quality, because it adds the most to the sum. So we need a structure that always hands out its largest value quickly, even while new values keep arriving.

A heap does that. Java's PriorityQueue class is one, and by default it keeps its smallest value on top. Given the comparator (a, b) -> Integer.compare(b, a), which reverses the order, it keeps the largest on top instead. A heap with the largest value on top is called a max-heap. Adding a value with add and taking the top one with poll each take about log k steps.

Follow Example 2. Sorted by rate, the workers are 2 and 3 (rate 0.2, quality 10 each), then 0 (rate 4/3, quality 3), then 4 (rate 7, quality 1), then 1 (rate 8, quality 1). After worker 0, the heap holds 10, 10 and 3, which sum to 23, and 23 × 4/3 is about 30.67. Worker 4 pushes out a 10, so the sum is 14 and the cost 14 × 7 = 98. Worker 1 pushes out the other 10, and 5 × 8 = 40. The smallest of the three costs is 30.67, the answer.

When the newest worker leaves at once

What if the newest worker has the largest quality in the heap? Then poll removes that worker right away, and the team left behind does not contain the one setting the rate. Its cost is then computed at a rate higher than the team needs. The same k qualities were already priced at the lower rate of an earlier worker, so this cost is never smaller than one already counted. Taking the minimum ignores it, and no special check is needed.

Java Solution

The method mincostToHireWorkers works in these steps:

  1. First, work out each worker's lowest rate into an array ratio, as (double) wage[i] / quality[i]. The cast to double keeps the fraction, so 50 / 20 gives 2.5 and not 2. An array order gets the worker numbers 0 to n - 1.
  2. Sort order by rate with Arrays.sort and the comparator Double.compare(ratio[a], ratio[b]). order is an Integer[], not an int[], because sorting with a comparator needs objects.
  3. Create the max-heap group, a PriorityQueue<Integer> with the comparator (a, b) -> Integer.compare(b, a). Next to it, qualitySum holds the sum of the qualities in the heap, and best starts at Double.MAX_VALUE, larger than any real cost.
  4. Walk through order with one loop, calling the current worker w. Add quality[w] to group and to qualitySum. If the heap now holds more than k qualities, poll removes the largest, and it is subtracted from qualitySum.
  5. When group holds exactly k qualities, price the team as qualitySum * ratio[w] and keep the smaller of that and best. Once every worker has had a turn, best holds the cheapest team, and the method returns it.

The main method runs both examples, Example 1 again with teams of one and of three, and a case where a pickier worker leads to a cheaper team.

Java
import java.util.Arrays;
import java.util.PriorityQueue;

public class MinimumCostToHireKWorkers {

    public static double mincostToHireWorkers(int[] quality, int[] wage, int k) {
        int n = quality.length;
        double[] ratio = new double[n];
        Integer[] order = new Integer[n];
        for (int i = 0; i < n; i++) {
            ratio[i] = (double) wage[i] / quality[i];   // pay this worker wants per unit
            order[i] = i;
        }
        Arrays.sort(order, (a, b) -> Double.compare(ratio[a], ratio[b]));

        // max-heap: the largest quality in the group sits on top
        PriorityQueue<Integer> group = new PriorityQueue<>((a, b) -> Integer.compare(b, a));
        long qualitySum = 0;
        double best = Double.MAX_VALUE;
        for (int w : order) {
            group.add(quality[w]);
            qualitySum += quality[w];
            if (group.size() > k) {
                qualitySum -= group.poll();             // drop the largest quality
            }
            if (group.size() == k) {
                best = Math.min(best, qualitySum * ratio[w]); // w sets the rate
            }
        }
        return best;
    }

    public static void main(String[] args) {
        System.out.printf("%.5f%n", mincostToHireWorkers(
                new int[] {10, 20, 5}, new int[] {70, 50, 30}, 2));
        System.out.printf("%.5f%n", mincostToHireWorkers(
                new int[] {3, 1, 10, 10, 1}, new int[] {4, 8, 2, 2, 7}, 3));
        System.out.printf("%.5f%n", mincostToHireWorkers(
                new int[] {10, 20, 5}, new int[] {70, 50, 30}, 1));
        System.out.printf("%.5f%n", mincostToHireWorkers(
                new int[] {10, 20, 5}, new int[] {70, 50, 30}, 3));
        System.out.printf("%.5f%n", mincostToHireWorkers(
                new int[] {1, 50, 2}, new int[] {1, 60, 4}, 2));
    }
}

Running it prints:

Output
105.00000
30.66667
30.00000
245.00000
6.00000

105.00000 and 30.66667 match the two examples. The 30.00000 is Example 1 with teams of one: a worker hired alone is paid exactly their wage, so the cheapest is worker 2 at 30. The 245.00000 hires all three, at worker 0's rate of 7 times the total quality 35.

Look at the last line, 6.00000. The workers have qualities 1, 50 and 2 and wages 1, 60 and 4, so their rates are 1, 1.2 and 2. With the second worker setting the rate, the team has qualities 1 and 50 and costs 1.2 × 51 = 61.2. The third worker raises the rate to 2, but quality 50 leaves the heap, and 2 × 3 = 6. A higher rate can still give the cheaper team.

Complexity

The work is the sort, plus a few heap steps for each worker.

  • Time: O(n log n), because sorting the n workers by rate takes about n log n steps, and each worker then makes one add and at most one poll, each O(log k) on a heap of k + 1 qualities.
  • Space: O(n), because ratio and order hold one entry per worker, and the heap holds at most k + 1 qualities on top of that.

Choosing a team by one limiting value while keeping the best k of another in a heap also solves Maximum Subsequence Score.