Created
October 8, 2021 04:23
-
-
Save shrishty/3f916c454b690ea55669cfcdf4f0442d to your computer and use it in GitHub Desktop.
Heapq Usage Example
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
class Solution(object): | |
def maxAverageRatio(self, classes, extraStudents): | |
maxHeap = [] | |
def delta(a, b): | |
return float(a + 1) / (b + 1) — float(a) / b | |
for a, b in classes: | |
heapq.heappush(maxHeap, (-delta(a, b), a, b)) | |
for _ in range(extraStudents): | |
d, a, b = heapq.heappop(maxHeap) | |
heapq.heappush(maxHeap, (-delta(a+1, b+1), a+1, b+1)) | |
ans = 0.0 | |
while maxHeap: | |
_, a, b = heapq.heappop(maxHeap) | |
ans += float(a) / b | |
return ans / len(classes) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment