Minimize deviation of an array by given operations | C ++ implementation of the above approach ; Function to find the minimum deviation of the array A [ ] ; Store all array elements in sorted order ; Odd number are transformed using 2 nd operation ; ( Maximum - Minimum ) ; Check if the size of set is > 0 and the maximum element is divisible by 2 ; Maximum element of the set ; Erase the maximum element ; Using operation 1 ; ( Maximum - Minimum ) ; Print the Minimum Deviation Obtained ; Driver Code ; Function Call to find Minimum Deviation of A [ ]
#include <bits/stdc++.h> NEW_LINE using namespace std ; void minimumDeviation ( int A [ ] , int N ) { set < int > s ; for ( int i = 0 ; i < N ; i ++ ) { if ( A [ i ] % 2 == 0 ) s . insert ( A [ i ] ) ; else s . insert ( 2 * A [ i ] ) ; } int diff = * s . rbegin ( ) - * s . begin ( ) ; while ( ( int ) s . size ( ) && * s . rbegin ( ) % 2 == 0 ) { int maxEl = * s . rbegin ( ) ; s . erase ( maxEl ) ; s . insert ( maxEl / 2 ) ; diff = min ( diff , * s . rbegin ( ) - * s . begin ( ) ) ; } cout << diff ; } int main ( ) { int A [ ] = { 4 , 1 , 5 , 20 , 3 } ; int N = sizeof ( A ) / sizeof ( A [ 0 ] ) ; minimumDeviation ( A , N ) ; return 0 ; }