🧠
Brute Force (Check All Subsets)
💡 This approach exists to understand the problem's core constraints and why naive enumeration is infeasible. It helps grasp the fairness condition and the ratio concept.
Intuition
Try every combination of K workers, calculate the pay ratio needed to satisfy all, and pick the minimum total cost.
Algorithm
- Generate all subsets of workers of size K.
- For each subset, find the maximum wage-to-quality ratio among its workers.
- Calculate total cost as this ratio multiplied by sum of qualities in the subset.
- Return the minimum total cost found.
💡 The challenge is understanding the fairness ratio and how it determines the total cost for each subset.
from itertools import combinations
def mincostToHireWorkers(quality, wage, K):
n = len(quality)
min_cost = float('inf')
for group in combinations(range(n), K):
max_ratio = 0
total_quality = 0
for i in group:
ratio = wage[i] / quality[i]
if ratio > max_ratio:
max_ratio = ratio
total_quality += quality[i]
cost = max_ratio * total_quality
if cost < min_cost:
min_cost = cost
return min_cost
# Driver code
if __name__ == '__main__':
quality = [10, 20, 5]
wage = [70, 50, 30]
K = 2
print(mincostToHireWorkers(quality, wage, K)) # Expected: 105.0
Line Notes
from itertools import combinationsImport combinations to generate all subsets of size K, essential for brute force enumeration.
for group in combinations(range(n), K):Enumerate every possible group of K workers to check all combinations.
max_ratio = 0Initialize max ratio for current group to find the fairness ratio that satisfies all workers.
ratio = wage[i] / quality[i]Calculate wage-to-quality ratio for each worker to determine minimum pay ratio.
cost = max_ratio * total_qualityCalculate total cost based on max ratio and sum of qualities, ensuring fairness.
if cost < min_cost:Update minimum cost if current group is cheaper, tracking the best solution.
import java.util.*;
public class Solution {
public static double mincostToHireWorkers(int[] quality, int[] wage, int K) {
int n = quality.length;
double minCost = Double.MAX_VALUE;
List<Integer> workers = new ArrayList<>();
for (int i = 0; i < n; i++) workers.add(i);
List<List<Integer>> combinations = new ArrayList<>();
combine(workers, K, 0, new ArrayList<>(), combinations);
for (List<Integer> group : combinations) {
double maxRatio = 0;
int totalQuality = 0;
for (int i : group) {
double ratio = (double) wage[i] / quality[i];
if (ratio > maxRatio) maxRatio = ratio;
totalQuality += quality[i];
}
double cost = maxRatio * totalQuality;
if (cost < minCost) minCost = cost;
}
return minCost;
}
private static void combine(List<Integer> arr, int k, int start, List<Integer> temp, List<List<Integer>> res) {
if (temp.size() == k) {
res.add(new ArrayList<>(temp));
return;
}
for (int i = start; i < arr.size(); i++) {
temp.add(arr.get(i));
combine(arr, k, i + 1, temp, res);
temp.remove(temp.size() - 1);
}
}
public static void main(String[] args) {
int[] quality = {10, 20, 5};
int[] wage = {70, 50, 30};
int K = 2;
System.out.println(mincostToHireWorkers(quality, wage, K)); // Expected: 105.0
}
}
Line Notes
List<Integer> workers = new ArrayList<>();Create list of worker indices for generating combinations.
combine(workers, K, 0, new ArrayList<>(), combinations);Generate all subsets of size K recursively to enumerate all groups.
double ratio = (double) wage[i] / quality[i];Calculate wage-to-quality ratio for fairness condition.
double cost = maxRatio * totalQuality;Compute total cost for current group based on max ratio and total quality.
#include <bits/stdc++.h>
using namespace std;
void combine(vector<int>& arr, int k, int start, vector<int>& temp, vector<vector<int>>& res) {
if ((int)temp.size() == k) {
res.push_back(temp);
return;
}
for (int i = start; i < (int)arr.size(); i++) {
temp.push_back(arr[i]);
combine(arr, k, i + 1, temp, res);
temp.pop_back();
}
}
double mincostToHireWorkers(vector<int>& quality, vector<int>& wage, int K) {
int n = (int)quality.size();
vector<int> workers(n);
iota(workers.begin(), workers.end(), 0);
vector<vector<int>> combinations;
vector<int> temp;
combine(workers, K, 0, temp, combinations);
double minCost = 1e15;
for (auto& group : combinations) {
double maxRatio = 0;
int totalQuality = 0;
for (int i : group) {
double ratio = (double)wage[i] / quality[i];
maxRatio = max(maxRatio, ratio);
totalQuality += quality[i];
}
double cost = maxRatio * totalQuality;
minCost = min(minCost, cost);
}
return minCost;
}
int main() {
vector<int> quality = {10, 20, 5};
vector<int> wage = {70, 50, 30};
int K = 2;
cout << mincostToHireWorkers(quality, wage, K) << "\n"; // Expected: 105.0
return 0;
}
Line Notes
iota(workers.begin(), workers.end(), 0);Fill workers vector with indices 0 to n-1 for combination generation.
combine(workers, K, 0, temp, combinations);Generate all combinations of size K recursively.
double ratio = (double)wage[i] / quality[i];Calculate wage-to-quality ratio for fairness.
minCost = min(minCost, cost);Update minimum cost if current group is cheaper.
function combine(arr, k, start, temp, res) {
if (temp.length === k) {
res.push([...temp]);
return;
}
for (let i = start; i < arr.length; i++) {
temp.push(arr[i]);
combine(arr, k, i + 1, temp, res);
temp.pop();
}
}
function mincostToHireWorkers(quality, wage, K) {
const n = quality.length;
const workers = Array.from({length: n}, (_, i) => i);
const combinations = [];
combine(workers, K, 0, [], combinations);
let minCost = Infinity;
for (const group of combinations) {
let maxRatio = 0;
let totalQuality = 0;
for (const i of group) {
const ratio = wage[i] / quality[i];
if (ratio > maxRatio) maxRatio = ratio;
totalQuality += quality[i];
}
const cost = maxRatio * totalQuality;
if (cost < minCost) minCost = cost;
}
return minCost;
}
// Driver code
const quality = [10, 20, 5];
const wage = [70, 50, 30];
const K = 2;
console.log(mincostToHireWorkers(quality, wage, K)); // Expected: 105.0
Line Notes
const workers = Array.from({length: n}, (_, i) => i);Create array of worker indices for combination generation.
combine(workers, K, 0, [], combinations);Generate all subsets of size K recursively.
const ratio = wage[i] / quality[i];Calculate wage-to-quality ratio for fairness.
if (cost < minCost) minCost = cost;Update minimum cost if current group is cheaper.
TimeO(n choose K * K)
SpaceO(n choose K * K)
We generate all subsets of size K (n choose K), and for each subset, we compute max ratio and sum quality in O(K). This is exponential and infeasible for large n.
💡 For n=20 and K=10, this means over 184,000 subsets, each requiring work, which is too slow for interviews.
Interview Verdict: TLE
This approach is too slow for large inputs but helps understand the problem and fairness condition.