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 [ ]
using System ; using System . Collections . Generic ; using System . Linq ; class GFG { static void minimumDeviation ( int [ ] A , int N ) { HashSet < int > s = new HashSet < int > ( ) ; for ( int i = 0 ; i < N ; i ++ ) { if ( A [ i ] % 2 == 0 ) s . Add ( A [ i ] ) ; else s . Add ( 2 * A [ i ] ) ; } List < int > S = s . ToList ( ) ; S . Sort ( ) ; int diff = S [ S . Count - 1 ] - S [ 0 ] ; while ( ( int ) S . Count != 0 && S [ S . Count - 1 ] % 2 == 0 ) { int maxEl = S [ S . Count - 1 ] ; S . RemoveAt ( S . Count - 1 ) ; S . Add ( maxEl / 2 ) ; S . Sort ( ) ; diff = Math . Min ( diff , S [ S . Count - 1 ] - S [ 0 ] ) ; } Console . Write ( diff ) ; } static void Main ( ) { int [ ] A = { 4 , 1 , 5 , 20 , 3 } ; int N = A . Length ; minimumDeviation ( A , N ) ; } }