Smallest subarray containing minimum and maximum values | C ++ implementation of above approach ; Function to return length of smallest subarray containing both maximum and minimum value ; find maximum and minimum values in the array ; iterate over the array and set answer to smallest difference between position of maximum and position of minimum value ; last occurrence of minValue ; last occurrence of maxValue ; Driver code
#include <bits/stdc++.h> NEW_LINE using namespace std ; int minSubarray ( int A [ ] , int n ) { int minValue = * min_element ( A , A + n ) ; int maxValue = * max_element ( A , A + n ) ; int pos_min = -1 , pos_max = -1 , ans = INT_MAX ; for ( int i = 0 ; i < n ; i ++ ) { if ( A [ i ] == minValue ) pos_min = i ; if ( A [ i ] == maxValue ) pos_max = i ; if ( pos_max != -1 and pos_min != -1 ) ans = min ( ans , abs ( pos_min - pos_max ) + 1 ) ; } return ans ; } int main ( ) { int A [ ] = { 1 , 5 , 9 , 7 , 1 , 9 , 4 } ; int n = sizeof ( A ) / sizeof ( A [ 0 ] ) ; cout << minSubarray ( A , n ) ; return 0 ; }