Maximize pair decrements required to reduce all array elements except one to 0 | Function to count maximum number of steps to make ( N - 1 ) array elements to 0 ; Stores maximum count of steps to make ( N - 1 ) elements equal to 0 ; Stores array elements ; Traverse the array ; Insert arr [ i ] into PQ ; Extract top 2 elements from the array while ( N - 1 ) array elements become 0 ; Stores top element of PQ ; Pop the top element of PQ . ; Stores top element of PQ ; Pop the top element of PQ . ; Update X ; Update Y ; If X is not equal to 0 ; Insert X into PQ ; if Y is not equal to 0 ; Insert Y into PQ ; Update cntOp ; Driver Code
def cntMaxOperationToMakeN_1_0 ( arr , N ) : NEW_LINE INDENT cntOp = 0 NEW_LINE PQ = [ ] NEW_LINE for i in range ( N ) : NEW_LINE INDENT PQ . append ( arr [ i ] ) NEW_LINE DEDENT PQ = sorted ( PQ ) NEW_LINE while ( len ( PQ ) > 1 ) : NEW_LINE INDENT X = PQ [ - 1 ] NEW_LINE del PQ [ - 1 ] NEW_LINE Y = PQ [ - 1 ] NEW_LINE del PQ [ - 1 ] NEW_LINE X -= 1 NEW_LINE Y -= 1 NEW_LINE if ( X != 0 ) : NEW_LINE INDENT PQ . append ( X ) NEW_LINE DEDENT if ( Y != 0 ) : NEW_LINE INDENT PQ . append ( Y ) NEW_LINE DEDENT cntOp += 1 NEW_LINE PQ = sorted ( PQ ) NEW_LINE DEDENT return cntOp NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT arr = [ 1 , 2 , 3 , 4 , 5 ] NEW_LINE N = len ( arr ) NEW_LINE print ( cntMaxOperationToMakeN_1_0 ( arr , N ) ) NEW_LINE DEDENT