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
#include <bits/stdc++.h> NEW_LINE using namespace std ; int minimumMaxDiff ( vector < int > & nums ) { set < int > s ; for ( int i = 0 ; i < nums . size ( ) ; i ++ ) { if ( nums [ i ] % 2 == 0 ) s . insert ( nums [ i ] ) ; else s . insert ( nums [ i ] * 2 ) ; } int res = * s . rbegin ( ) - * s . begin ( ) ; while ( * s . rbegin ( ) % 2 == 0 ) { int x = * s . rbegin ( ) ; s . erase ( x ) ; s . insert ( x / 2 ) ; res = min ( res , * s . rbegin ( ) - * s . begin ( ) ) ; } return res ; } int main ( ) { vector < int > arr = { 1 , 2 , 5 , 9 } ; cout << minimumMaxDiff ( arr ) ; }