Skip to content

Instantly share code, notes, and snippets.

@shrishty
Created October 8, 2021 04:23
Show Gist options
  • Save shrishty/3f916c454b690ea55669cfcdf4f0442d to your computer and use it in GitHub Desktop.
Save shrishty/3f916c454b690ea55669cfcdf4f0442d to your computer and use it in GitHub Desktop.
Heapq Usage Example
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