Minimize deviation of an array by given operations | Java program for 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 [ ]
import java . io . * ; import java . util . * ; class GFG { static void minimumDeviation ( int A [ ] , int N ) { TreeSet < Integer > s = new TreeSet < Integer > ( ) ; for ( int i = 0 ; i < N ; i ++ ) { if ( A [ i ] % 2 == 0 ) s . add ( A [ i ] ) ; else s . add ( 2 * A [ i ] ) ; } int diff = s . last ( ) - s . first ( ) ; while ( ( s . last ( ) % 2 == 0 ) ) { int maxEl = s . last ( ) ; s . remove ( maxEl ) ; s . add ( maxEl / 2 ) ; diff = Math . min ( diff , s . last ( ) - s . first ( ) ) ; } System . out . print ( diff ) ; } public static void main ( String [ ] args ) { int A [ ] = { 4 , 1 , 5 , 20 , 3 } ; int N = A . length ; minimumDeviation ( A , N ) ; } }