Maximize pair decrements required to reduce all array elements except one to 0 | Java program to implement the above approach ; 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
import java . util . * ; class GFG { static int cntMaxOperationToMakeN_1_0 ( int [ ] arr , int N ) { int cntOp = 0 ; PriorityQueue < Integer > PQ = new PriorityQueue < Integer > ( ( a , b ) -> b - a ) ; for ( int i = 0 ; i < N ; i ++ ) { PQ . add ( arr [ i ] ) ; } while ( PQ . size ( ) > 1 ) { int X = PQ . peek ( ) ; PQ . remove ( ) ; int Y = PQ . peek ( ) ; PQ . remove ( ) ; X -- ; Y -- ; if ( X != 0 ) { PQ . add ( X ) ; } if ( Y != 0 ) { PQ . add ( Y ) ; } cntOp += 1 ; } return cntOp ; } public static void main ( String [ ] args ) { int [ ] arr = { 1 , 2 , 3 , 4 , 5 } ; int N = arr . length ; System . out . print ( cntMaxOperationToMakeN_1_0 ( arr , N ) ) ; } }