Minimize the maximum difference of any pair by doubling odd elements and reducing even elements by half | Java program for the above approach ; Function to minimize the maximum difference between any pair of elements of the array by the given operations ; Traverse the array ; If current element is even ; Insert it into even ; Otherwise ; Make it even by multiplying by 2 and insert it into set ; Calculate difference between first and the last element of the set ; Iterate until difference is minimized ; Erase the current element ; Reduce current element by half and insert it into the Set ; Update difference ; Return the resultant difference ; Driver code
import java . io . * ; import java . util . * ; class GFG { static int minimumMaxDiff ( int [ ] nums ) { TreeSet < Integer > s = new TreeSet < Integer > ( ) ; for ( int i = 0 ; i < nums . length ; i ++ ) { if ( nums [ i ] % 2 == 0 ) s . add ( nums [ i ] ) ; else s . add ( nums [ i ] * 2 ) ; } int res = s . last ( ) - s . first ( ) ; while ( s . last ( ) % 2 == 0 ) { int x = s . last ( ) ; s . remove ( x ) ; s . add ( x / 2 ) ; res = Math . min ( res , s . last ( ) - s . first ( ) ) ; } return res ; } public static void main ( String [ ] args ) { int [ ] arr = new int [ ] { 1 , 2 , 5 , 9 } ; System . out . print ( minimumMaxDiff ( arr ) ) ; } }