KatInterview

887. Minimum Cost to Hire K Workers

HardSolutions in Python, Java, C++, TypeScript

Read the full problem statement on LeetCode and try it first. Below is how to approach it in an interview, followed by a complete answer in each language.

Approach

The problem asks for the minimum cost to hire exactly k workers, subject to two rules:

Solution

Minimum Cost to Hire K Workers in Python

import heapq

class Solution:
    def mincostToHireWorkers(self, quality: List[int], wage: List[int], k: int) -> float:
        # Create a list of workers with their wage-to-quality ratio and quality
        # and sort them by ratio.
        workers = sorted([(w / q, q) for w, q in zip(wage, quality)])

        min_cost = float('inf')
        quality_sum = 0
        # Max-heap to store qualities of the current group of k workers.
        # Python's heapq is a min-heap, so we store negative qualities to simulate a max-heap.
        quality_heap = []

        for ratio, qual in workers:
            # Add current worker's quality to the sum and the heap
            quality_sum += qual
            heapq.heappush(quality_heap, -qual)

            # If we have more than k workers, remove the one with the highest quality.
            # This maintains a group of k workers with the smallest qualities seen so far.
            if len(quality_heap) > k:
                # The highest quality is the smallest negative number in the min-heap
                highest_qual = -heapq.heappop(quality_heap)
                quality_sum -= highest_qual
            
            # If we have exactly k workers, calculate the cost and update min_cost.
            # The current 'ratio' is the highest ratio for this group of k workers.
            if len(quality_heap) == k:
                min_cost = min(min_cost, ratio * quality_sum)

        return min_cost

Minimum Cost to Hire K Workers in Java

class Solution {
    // Inner class to represent a worker with their ratio and quality
    class Worker implements Comparable<Worker> {
        double ratio;
        int quality;

        public Worker(double ratio, int quality) {
            this.ratio = ratio;
            this.quality = quality;
        }

        // Sort by ratio
        @Override
        public int compareTo(Worker other) {
            return Double.compare(this.ratio, other.ratio);
        }
    }

    public double mincostToHireWorkers(int[] quality, int[] wage, int k) {
        int n = quality.length;
        List<Worker> workers = new ArrayList<>();
        for (int i = 0; i < n; i++) {
            workers.add(new Worker((double) wage[i] / quality[i], quality[i]));
        }

        // Sort workers based on their wage-to-quality ratio
        Collections.sort(workers);

        double minCost = Double.MAX_VALUE;
        int qualitySum = 0;
        // Max-heap to store qualities. In Java, PriorityQueue is a min-heap by default,
        // so we use Collections.reverseOrder() to make it a max-heap.
        PriorityQueue<Integer> qualityHeap = new PriorityQueue<>(Collections.reverseOrder());

        for (Worker worker : workers) {
            // Add current worker to the group candidate
            qualitySum += worker.quality;
            qualityHeap.offer(worker.quality);

            // If group size exceeds k, remove the one with the highest quality
            if (qualityHeap.size() > k) {
                qualitySum -= qualityHeap.poll();
            }

            // If group size is exactly k, calculate the cost for this group
            // The current worker's ratio is the group's ratio because of the sorting
            if (qualityHeap.size() == k) {
                minCost = Math.min(minCost, worker.ratio * qualitySum);
            }
        }
        return minCost;
    }
}

Minimum Cost to Hire K Workers in C++

class Solution {
public:
    double mincostToHireWorkers(vector<int>& quality, vector<int>& wage, int k) {
        int n = quality.size();
        // Create a vector of pairs to store (ratio, quality) for each worker
        vector<pair<double, int>> workers;
        for (int i = 0; i < n; ++i) {
            workers.push_back({(double)wage[i] / quality[i], quality[i]});
        }

        // Sort workers based on their wage-to-quality ratio in ascending order
        sort(workers.begin(), workers.end());

        double minCost = DBL_MAX;
        int qualitySum = 0;
        // Max-heap to store the qualities of the k workers in the current group candidate.
        // By default, priority_queue in C++ is a max-heap.
        priority_queue<int> qualityHeap;

        // Iterate through the sorted workers
        for (int i = 0; i < n; ++i) {
            double ratio = workers[i].first;
            int qual = workers[i].second;

            // Add current worker's quality to the sum and the heap
            qualitySum += qual;
            qualityHeap.push(qual);

            // If the group size exceeds k, remove the worker with the highest quality
            // to maintain the k smallest qualities, minimizing the qualitySum.
            if (qualityHeap.size() > k) {
                qualitySum -= qualityHeap.top();
                qualityHeap.pop();
            }

            // If we have exactly k workers, this forms a valid group.
            // The current worker's ratio is the highest in this group.
            // Calculate the cost and update minCost if it's smaller.
            if (qualityHeap.size() == k) {
                minCost = min(minCost, ratio * qualitySum);
            }
        }

        return minCost;
    }
};

Minimum Cost to Hire K Workers in TypeScript

// Since TypeScript/JavaScript standard library doesn't include a PriorityQueue,
// a basic implementation is provided here for the solution.
class PriorityQueue<T> {
    private heap: T[];
    private comparator: (a: T, b: T) => number;

    constructor(comparator: (a: T, b: T) => number) {
        this.heap = [];
        this.comparator = comparator; // Determines min-heap or max-heap
    }

    size(): number {
        return this.heap.length;
    }

    peek(): T | undefined {
        return this.heap[0];
    }

    push(value: T): void {
        this.heap.push(value);
        this.siftUp();
    }

    pop(): T | undefined {
        if (this.size() <= 1) {
            return this.heap.pop();
        }
        const poppedValue = this.peek();
        this.heap[0] = this.heap.pop()!;
        this.siftDown();
        return poppedValue;
    }

    private parent(i: number): number { return Math.floor((i - 1) / 2); }
    private left(i: number): number { return 2 * i + 1; }
    private right(i: number): number { return 2 * i + 2; }

    private compare(i: number, j: number): boolean {
        return this.comparator(this.heap[i], this.heap[j]) > 0;
    }

    private swap(i: number, j: number): void {
        [this.heap[i], this.heap[j]] = [this.heap[j], this.heap[i]];
    }

    private siftUp(): void {
        let nodeIdx = this.size() - 1;
        while (nodeIdx > 0 && this.compare(nodeIdx, this.parent(nodeIdx))) {
            this.swap(nodeIdx, this.parent(nodeIdx));
            nodeIdx = this.parent(nodeIdx);
        }
    }

    private siftDown(): void {
        let nodeIdx = 0;
        while (
            (this.left(nodeIdx) < this.size() && this.compare(this.left(nodeIdx), nodeIdx)) ||
            (this.right(nodeIdx) < this.size() && this.compare(this.right(nodeIdx), nodeIdx))
        ) {
            let greaterChildIdx = this.left(nodeIdx);
            if (
                this.right(nodeIdx) < this.size() &&
                this.compare(this.right(nodeIdx), this.left(nodeIdx))
            ) {
                greaterChildIdx = this.right(nodeIdx);
            }
            this.swap(nodeIdx, greaterChildIdx);
            nodeIdx = greaterChildIdx;
        }
    }
}

function mincostToHireWorkers(quality: number[], wage: number[], k: number): number {
    const n = quality.length;
    
    // Create an array of worker objects with ratio and quality
    const workers = [];
    for (let i = 0; i < n; i++) {
        workers.push({ ratio: wage[i] / quality[i], quality: quality[i] });
    }

    // Sort workers by their wage-to-quality ratio
    workers.sort((a, b) => a.ratio - b.ratio);

    let minCost = Infinity;
    let qualitySum = 0;
    
    // Max-heap to store qualities. The comparator (a, b) => a - b makes it a max-heap.
    const qualityHeap = new PriorityQueue<number>((a, b) => a - b);

    for (const worker of workers) {
        // Add current worker's quality to the sum and the heap
        qualitySum += worker.quality;
        qualityHeap.push(worker.quality);

        // If we have more than k workers, remove the one with the highest quality
        if (qualityHeap.size() > k) {
            const highestQuality = qualityHeap.pop()!;
            qualitySum -= highestQuality;
        }

        // If we have exactly k workers, calculate cost and update minimum
        if (qualityHeap.size() === k) {
            minCost = Math.min(minCost, worker.ratio * qualitySum);
        }
    }

    return minCost;
};

Preparing for interviews beyond LeetCode? Practise system design, SQL and behavioral questions with an in-browser runner on KatInterview.

LeetCode is a trademark of LeetCode LLC. KatInterview is not affiliated with LeetCode.