Minimize the maximum difference of any pair by doubling odd elements and reducing even elements by half | C # 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
using System ; using System . Collections . Generic ; using System . Linq ; class GFG { static int minimumMaxDiff ( int [ ] nums ) { HashSet < int > s = new HashSet < int > ( ) ; 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 ; } static public void Main ( ) { int [ ] arr = new int [ ] { 1 , 2 , 5 , 9 } ; Console . WriteLine ( minimumMaxDiff ( arr ) ) ; } }