Skip to content

Commit 2d3661d

Browse files
authored
Create maximum-average-pass-ratio.py
1 parent 76d112c commit 2d3661d

File tree

1 file changed

+24
-0
lines changed

1 file changed

+24
-0
lines changed

Python/maximum-average-pass-ratio.py

Lines changed: 24 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,24 @@
1+
# Time: O(n + mlogn)
2+
# Space: O(n)
3+
4+
import heapq
5+
6+
7+
class Solution(object):
8+
def maxAverageRatio(self, classes, extraStudents):
9+
"""
10+
:type classes: List[List[int]]
11+
:type extraStudents: int
12+
:rtype: float
13+
"""
14+
def profit(a, b):
15+
return float(a+1)/(b+1)-float(a)/b
16+
17+
max_heap = [(-profit(a, b), a, b) for a, b in classes]
18+
heapq.heapify(max_heap)
19+
while extraStudents:
20+
v, a, b = heapq.heappop(max_heap)
21+
a, b = a+1, b+1
22+
heapq.heappush(max_heap, (-profit(a, b), a, b))
23+
extraStudents -= 1
24+
return sum(float(a)/b for v, a, b in max_heap)/len(classes)

0 commit comments

Comments
 (0)