Minimum distance between the maximum and minimum element of a given Array | Java Program to implement the above approach ; Function to find the minimum distance between the minimum and the maximum element ; Stores the minimum and maximum array element ; Stores the most recently traversed indices of the minimum and the maximum element ; Stores the minimum distance between the minimum and the maximium ; Find the maximum and the minimum element from the given array ; Find the minimum distance ; Check if current element is equal to minimum ; Check if current element is equal to maximum ; If both the minimum and the maximum element has occurred at least once ; Driver Code
import java . util . * ; class GFG { public static int minDistance ( int a [ ] , int n ) { int max = - 1 , min = Integer . MAX_VALUE ; int min_index = - 1 , max_index = - 1 ; int min_dist = n + 1 ; for ( int i = 0 ; i < n ; i ++ ) { if ( a [ i ] > max ) max = a [ i ] ; if ( a [ i ] < min ) min = a [ i ] ; } for ( int i = 0 ; i < n ; i ++ ) { if ( a [ i ] == min ) min_index = i ; if ( a [ i ] == max ) max_index = i ; if ( min_index != - 1 && max_index != - 1 ) min_dist = Math . min ( min_dist , Math . abs ( min_index - max_index ) ) ; } return min_dist ; } public static void main ( String [ ] args ) { int n = 12 ; int a [ ] = { 3 , 2 , 1 , 2 , 1 , 4 , 5 , 8 , 6 , 7 , 8 , 2 } ; System . out . println ( minDistance ( a , n ) ) ; } }