Skip to content

Commit 0d25fbb

Browse files
authored
Add files via upload
1 parent a8b4485 commit 0d25fbb

File tree

1 file changed

+76
-0
lines changed

1 file changed

+76
-0
lines changed

Top_K_Elements/min_cost.py

+76
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,76 @@
1+
import heapq
2+
3+
class Solution:
4+
def min_cost_to_hire_workers(self, quality, wage, k):
5+
6+
# Create list of tuples with wage/quality ratio
7+
workers = sorted([(w/q, q) for w, q in zip(wage, quality)])
8+
9+
# Initialize max heap
10+
heap = []
11+
12+
# Sum of qualities of selected workers
13+
total_quality = 0
14+
15+
# Initialize minimum cost
16+
min_cost = float('inf')
17+
18+
# Iterate through workers sorted by wage-to-quality ratio
19+
for ratio, q in workers:
20+
21+
# Add worker quality to heap
22+
heapq.heappush(heap, -q)
23+
total_quality += q
24+
25+
# More than k workers, remove largest quality
26+
if len(heap) > k:
27+
total_quality += heapq.heappop(heap)
28+
29+
# Exactly k workers, calculate cost
30+
if len(heap) == k:
31+
min_cost = min(min_cost, ratio * total_quality)
32+
33+
return min_cost
34+
35+
36+
37+
# Time Complexity = O(nlogk)
38+
# Space Complexity = O(k)
39+
40+
41+
42+
############################################################################
43+
44+
45+
46+
# Driver code
47+
def main():
48+
qualities = [
49+
[10, 20, 5],
50+
[3, 1, 10, 10, 1],
51+
[4, 5, 6],
52+
[2, 3, 1],
53+
[10, 10, 10]
54+
]
55+
56+
wages = [
57+
[70, 50, 30],
58+
[4, 8, 2, 2, 7],
59+
[8, 10, 12],
60+
[5, 6, 2],
61+
[50, 60, 70]
62+
]
63+
64+
k_values = [2, 3, 2, 2, 2]
65+
sol = Solution()
66+
for i in range(len(qualities)):
67+
print(i+1, ".\tqualities:", qualities[i])
68+
print("\twages:", wages[i])
69+
print("\tk:", k_values[i])
70+
result = sol.min_cost_to_hire_workers(qualities[i], wages[i], k_values[i])
71+
print("\n\tMinimum cost to hire", k_values[i], "workers =", result)
72+
print("-"*100)
73+
74+
if __name__ == "__main__":
75+
main()
76+

0 commit comments

Comments
 (0)