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
function cntMaxOperationToMakeN_1_0 ( arr , N ) { let cntOp = 0 ; let PQ = [ ] ; for ( let i = 0 ; i < N ; i ++ ) { PQ . push ( arr [ i ] ) ; } PQ . sort ( function ( a , b ) { return a - b } ) ; PQ . reverse ( ) ; while ( PQ . length > 1 ) { let X = PQ [ 0 ] ; PQ . shift ( ) ; let Y = PQ [ 0 ] ; PQ . shift ( ) ; X -- ; Y -- ; if ( X != 0 ) { PQ . push ( X ) ; PQ . sort ( function ( a , b ) { return a - b } ) ; PQ . reverse ( ) ; } if ( Y != 0 ) { PQ . push ( Y ) ; PQ . sort ( function ( a , b ) { return a - b } ) ; PQ . reverse ( ) ; } cntOp += 1 ; } return cntOp ; } let arr = [ 1 , 2 , 3 , 4 , 5 ] ; let N = arr . length ; document . write ( cntMaxOperationToMakeN_1_0 ( arr , N ) ) ;