Minimize swaps required to make the first and last elements the largest and smallest elements in the array respectively | C ++ program for the above approach ; Function to find the minimum number of swaps required to make the first and the last elements the largest and smallest element in the array ; Stores the count of swaps ; Stores the maximum element ; Stores the minimum element ; If the array contains a single distinct element ; Stores the indices of the maximum and minimum elements ; If the first index of the maximum element is found ; If current index has the minimum element ; Update the count of operations to place largest element at the first ; Update the count of operations to place largest element at the last ; If smallest element is present before the largest element initially ; Driver Code
#include <bits/stdc++.h> NEW_LINE using namespace std ; int minimum_swaps ( int arr [ ] , int n ) { int count = 0 ; int max_el = * max_element ( arr , arr + n ) ; int min_el = * min_element ( arr , arr + n ) ; if ( min_el == max_el ) return 0 ; int index_max = -1 ; int index_min = -1 ; for ( int i = 0 ; i < n ; i ++ ) { if ( arr [ i ] == max_el && index_max == -1 ) { index_max = i ; } if ( arr [ i ] == min_el ) { index_min = i ; } } count += index_max ; count += ( n - 1 - index_min ) ; if ( index_min < index_max ) count -= 1 ; return count ; } int main ( ) { int arr [ ] = { 2 , 4 , 1 , 6 , 5 } ; int N = sizeof ( arr ) / sizeof ( arr [ 0 ] ) ; cout << minimum_swaps ( arr , N ) ; return 0 ; }