Maximize average of the ratios of N pairs by M increments | Function to find the change in the ratio in pair after applying operation ; Stores the current ratio ; Stores the new ratio ; Stores the increase in ratio ; Returns the change ; Function to find the maximum average of the ratio of the pairs by applying M increments ; Stores the required result ; Declare a priority queue for storing the increments ; Store the increase in the ratio after applying one operation ; Push the increased value and index value in priority queue ; Store the ratio ; Update the value of sum ; Iterate while M > 0 ; Add the maximum change to the sum ; Remove the element from the priority queue ; Increase the pairs elements by 1 on which operation is applied ; Push the updated change of the pair in priority queue ; Decrease the operation count ; Update the value of the sum by dividing it by N ; Return the result ; Driver Code
def change ( pas , total ) : NEW_LINE INDENT currentPassRatio = pas / total NEW_LINE newPassRatio = ( pas + 1 ) / ( total + 1 ) NEW_LINE increase = newPassRatio - currentPassRatio NEW_LINE return increase NEW_LINE DEDENT def maximumAverage ( v , M , N ) : NEW_LINE INDENT sum = 0 NEW_LINE increase , average = 0 , 0 NEW_LINE pq = [ ] NEW_LINE for i in range ( N ) : NEW_LINE INDENT increase = change ( v [ i ] [ 0 ] , v [ i ] [ 1 ] ) NEW_LINE pq . append ( [ increase , i ] ) NEW_LINE average = v [ i ] [ 0 ] * 1.0 / v [ i ] [ 1 ] NEW_LINE sum += average NEW_LINE DEDENT pq = sorted ( pq ) NEW_LINE while ( M > 0 ) : NEW_LINE INDENT sum += pq [ - 1 ] [ 0 ] NEW_LINE i = pq [ - 1 ] [ 1 ] NEW_LINE del pq [ - 1 ] NEW_LINE v [ i ] [ 0 ] += 1 NEW_LINE v [ i ] [ 1 ] += 1 NEW_LINE pq . append ( [ change ( v [ i ] [ 0 ] , v [ i ] [ 1 ] ) , i ] ) NEW_LINE M -= 1 NEW_LINE pq = sorted ( pq ) NEW_LINE DEDENT ans = sum / N NEW_LINE return ans NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT V = [ [ 1 , 2 ] , [ 3 , 5 ] , [ 2 , 2 ] ] NEW_LINE M = 2 NEW_LINE N = len ( V ) NEW_LINE print ( round ( maximumAverage ( V , M , N ) , 6 ) ) NEW_LINE DEDENT