Minimum distance between the maximum and minimum element of a given Array | C ++ 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
#include <bits/stdc++.h> NEW_LINE using namespace std ; int minDistance ( int a [ ] , int n ) { int maximum = -1 , minimum = INT_MAX ; int min_index = -1 , max_index = -1 ; int min_dist = n + 1 ; for ( int i = 0 ; i < n ; i ++ ) { if ( a [ i ] > maximum ) maximum = a [ i ] ; if ( a [ i ] < minimum ) minimum = a [ i ] ; } for ( int i = 0 ; i < n ; i ++ ) { if ( a [ i ] == minimum ) min_index = i ; if ( a [ i ] == maximum ) max_index = i ; if ( min_index != -1 && max_index != -1 ) min_dist = min ( min_dist , abs ( min_index - max_index ) ) ; } return min_dist ; } int main ( ) { int a [ ] = { 3 , 2 , 1 , 2 , 1 , 4 , 5 , 8 , 6 , 7 , 8 , 2 } ; int n = sizeof a / sizeof a [ 0 ] ; cout << minDistance ( a , n ) ; }