Intuition

Complexity

Runtime

Space

Code

class Solution:
    def maxAverageRatio(self, classes: List[List[int]], extraStudents: int) -> float:
        def calculate_gain(s, c):
            return ((s + 1) / (c + 1)) - (s / c)
 
        heap = []
        for c in classes:
            heappush(heap, (-calculate_gain(c[0], c[1]), c[0], c[1]))
        
        for _ in range(extraStudents):
            r, s, c = heappop(heap)
            s += 1
            c += 1
 
            new_gain = calculate_gain(s, c)
            heappush(heap, (-new_gain, s, c))
        
        res = 0
        for _, s, c in heap:
            res += s / c
        
        return res / len(classes)

Notes

Cards


References