Minimum Cost to Hire K Workers solution explained

Minimum Cost to Hire K Workers asks for the cheapest way to hire exactly k people when pay inside the group must be proportional to quality and nobody may be paid below their minimum. A group's cost is its highest wage-to-quality ratio times its total quality. Sort workers by that ratio, and for each worker as the highest ratio keep the k smallest qualities seen so far in a max-heap. That gives the minimum in O(n log n).

By Published 9 min read

The problem, in plain terms

There are n candidates. Candidate i has a quality score q[i] and a minimum acceptable pay m[i]. You must hire exactly k of them under two rules: within the hired group, pay is proportional to quality (someone with twice the quality gets twice the pay), and every hire is paid at least their minimum. Return the lowest possible total pay for the group, as a real number.

candidate   0     1     2     3
quality     4     2     5     1
minimum     20    6     30    8
ratio       5.0   3.0   6.0   8.0      (minimum / quality)

group {1, 0}: rate 5.0, qualities 2 + 4 = 6    cost 30
group {1, 2}: rate 6.0, qualities 2 + 5 = 7    cost 42
group {3, 1}: rate 8.0, qualities 1 + 2 = 3    cost 24   <- cheapest
answer: 24.0
Four candidates and k = 2, made up for this page

The cheapest group contains the candidate with the worst ratio. Candidate 3 asks for a high rate per unit of quality, but has so little quality that the whole group stays small. That is why neither "pick the lowest ratios" nor "pick the lowest minimums" works on its own: the cost is a product, and you have to trade one factor against the other.

Ask before coding: must the group be exactly k, not at most k? How precise must the answer be? Can two candidates share a ratio? Are qualities and minimums positive integers? Exactly k, and positive values, are what the rest of this page assumes.

Turning the rules into a formula

Proportional pay means every hire gets r × q[i] for one shared rate r. The minimum rule says r × q[i] ≥ m[i], so r ≥ m[i] / q[i] for everyone in the group. To pay as little as possible, pick the smallest legal r, which is the largest ratio in the group. Total pay is then r × (sum of qualities in the group). Getting to this formula out loud is half the interview; the rest is optimizing a product of a maximum and a sum.

Why it is asked

It is a hard-level heap problem with a modeling step in front. Interviewers use it to see whether you can derive the cost formula yourself, then whether you know the standard move for "maximum of one thing times sum of another": fix the maximum by sorting, then choose the best sum among the items that the fixed maximum allows.

Brute force: every group of k

Try all groups of size k and apply the formula. Exact fractions avoid any rounding doubt, which makes this the right reference for checking the fast version, but there are n choose k groups.

from fractions import Fraction
from itertools import combinations


def hire_cost_slow(quality, minimum, k):
    best = None
    for group in combinations(range(len(quality)), k):
        rate = max(Fraction(minimum[i], quality[i]) for i in group)
        cost = rate * sum(quality[i] for i in group)
        if best is None or cost < best:
            best = cost
    return best
Python: every combination, exact arithmetic. Exponential time.

Optimal approach: sort by ratio, heap of qualities

Sort candidates by ratio, lowest first. Walk the list. When you reach candidate j, every candidate before it has a ratio no larger, so if j joins a group drawn from the first j + 1 candidates, j's ratio is the group rate. With the rate fixed, the best group is the one with the smallest total quality: j plus the k - 1 smallest qualities before it. Keep the k smallest qualities seen so far in a max-heap with a running sum. After pushing q[j], if the heap holds more than k, pop the largest. Once it holds exactly k, evaluate ratio[j] × sum.

import heapq


def hire_cost(quality, minimum, k):
    order = sorted(range(len(quality)), key=lambda i: minimum[i] / quality[i])
    kept, total, best = [], 0, float("inf")
    for i in order:
        heapq.heappush(kept, -quality[i])
        total += quality[i]
        if len(kept) > k:
            total += heapq.heappop(kept)  # removes the largest quality
        if len(kept) == k:
            best = min(best, minimum[i] / quality[i] * total)
    return best
Python: sort plus a max-heap (negated values). O(n log n) time, O(k) heap.

A subtle point that interviewers sometimes probe: when q[j] is itself the largest and gets popped right away, the evaluated group does not contain j at all. The formula then uses j's ratio with a group whose true rate is lower, so the number computed is too high, never too low. Since the minimum only cares about values that can win, these overestimates are harmless, and the true optimum is still evaluated when its own highest-ratio member is processed.

#include <algorithm>
#include <limits>
#include <numeric>
#include <queue>
#include <vector>

double hireCost(const std::vector<int>& quality, const std::vector<int>& minimum, int k) {
    int n = quality.size();
    std::vector<int> order(n);
    std::iota(order.begin(), order.end(), 0);
    std::sort(order.begin(), order.end(), [&](int a, int b) {
        // compare minimum[a]/quality[a] with minimum[b]/quality[b] without division
        return (long long)minimum[a] * quality[b] < (long long)minimum[b] * quality[a];
    });

    std::priority_queue<int> kept;  // largest quality on top
    long long total = 0;
    double best = std::numeric_limits<double>::infinity();
    for (int i : order) {
        kept.push(quality[i]);
        total += quality[i];
        if ((int)kept.size() > k) {
            total -= kept.top();
            kept.pop();
        }
        if ((int)kept.size() == k)
            best = std::min(best, (double)minimum[i] / quality[i] * total);
    }
    return best;
}
C++17: the same idea with a default max-heap of qualities

The C++ sort compares ratios by cross-multiplying, so the order is exact even when two ratios differ only in a late decimal place. Only the final multiplication uses floating point, and the answer is expected as a real number anyway.

Complexity summary

n candidates, groups of exactly k
ApproachTimeExtra memoryNote
Every group of kO(C(n, k) × k)O(k)Exact reference for small n
Fix the rate, then sort qualitiesO(n² log n)O(n)Correct, too slow for large n
Sort by ratio plus max-heapO(n log n)O(n) for the order, O(k) heapExpected answer
n candidates, groups of exactly k. Scroll sideways on a small screen.

Edge cases to try

  • k = 1: the answer is the smallest minimum, since a lone hire is paid exactly that.
  • k = n: everyone is hired, so the answer is the largest ratio times the total quality.
  • Several candidates with the same ratio: ties in the sort do not change the answer.
  • One candidate with tiny quality and a huge ratio, as in the example: they can still be in the best group.
  • Large qualities and minimums: in C++, products for the sort need 64-bit integers.

Mistakes to avoid

  • Picking the k lowest ratios, or the k lowest minimums, which ignores the other factor of the cost.
  • Using a min-heap of qualities and evicting the smallest, the opposite of what keeps the sum low.
  • Evaluating the cost before the heap has k items, producing groups that are too small.
  • Recomputing the sum of the heap each time instead of keeping a running total, which adds an O(k) factor.
  • Sorting by floating-point ratios in a language where precision matters, then being surprised by ties that are not really ties.

Follow-ups

  • Return the group, not just the cost. Record the index j where the best value was found, then rerun the loop up to j and read the heap's contents.
  • Hire at most k. The answer collapses to the single smallest minimum, because dropping someone from a group never raises the rate or the quality sum. That is why the problem insists on exactly k.
  • Add a budget and maximize the number of hires. Binary search on k and reuse this algorithm as the check, since cost does not decrease as k grows.
  • Exact output. Keep the best value as a fraction (numerator times quality sum over denominator) and compare by cross-multiplication.

How to explain it out loud

Fictional example

From the rules to the heap
Candidate
Everyone gets the same rate per unit of quality, and the rate must be at least each person's minimum over quality. So the group's rate is its largest ratio, and the cost is that ratio times the group's total quality.
Candidate
If I sort by ratio, then the person I am looking at has the highest ratio among everyone before them. Fixing them as the rate setter, I want the smallest total quality from the people up to here.
Candidate
A max-heap keeps the k smallest qualities: push the new one, pop the largest if there are too many, and keep a running sum.
Interviewer
What if the person you just pushed gets popped?
Candidate
Then the group I evaluate uses a rate that is higher than it needs, so the cost is an overestimate. It can never beat the true optimum, which I evaluate when its own top-ratio member comes up.

IPO also sorts by one key and keeps a heap over another to make the best choice. Furthest Building You Can Reach maintains a heap of the best few items seen so far and evicts the weakest. Find K Pairs with Smallest Sums is a different heap shape, a frontier over a sorted grid. Top K Frequent Elements practices keeping the k best items with a heap.

Practicing it with Natively

This is one of those problems where the derivation matters more than the code, so rehearse saying it. On Mac or Windows, Natively can read the problem from a screenshot during practice and lay out the ratio-and-heap approach, including the overestimate argument, and its transcript of your mock interview lets you check whether you derived the cost formula or skipped to it. The AI interview assistant page explains the practice setup.

Questions people ask

How do you solve Minimum Cost to Hire K Workers?

A group's cost is its largest wage-to-quality ratio times its total quality. Sort workers by ratio, walk the list, keep the k smallest qualities in a max-heap with a running sum, and once the heap holds k, compute the current ratio times the sum. The smallest value is the answer.

Why sort by wage-to-quality ratio?

Pay must be proportional to quality and at least each minimum, so the group rate is the highest ratio in the group. Sorting makes the current worker's ratio the highest so far, which fixes the rate and leaves only the quality sum to minimize.

What is the time complexity of Minimum Cost to Hire K Workers?

O(n log n) for the sort and the heap operations, with O(n) memory for the sorted order and O(k) for the heap.

Why use a max-heap of qualities?

To keep the k smallest qualities seen so far, you need to remove the largest one whenever a new quality makes the heap too big. A max-heap puts that largest quality on top.

Where to go next

Practice with the same assistant you would use on a call: it listens, transcribes and suggests answers from your own resume and the job description.

Facts on this page were last checked on . Product details come from the Natively app itself; if something here is out of date, tell us at hello@heynatively.com.

Keep reading

Put it on your own machine.

A live-conversation assistant that runs locally. Your conversations stay on your machine.

macOS 12+ · Windows 10/11

© 2026 Natively AI Private Limited

Source-available under the Natively Personal Use Source License v1.0 · IP geolocation by DB-IP