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
using System ; using System . Linq ; class GFG { static int minimum_swaps ( int [ ] arr , int n ) { int count = 0 ; int max_el = arr . Max ( ) ; int min_el = arr . Min ( ) ; 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 ; } public static void Main ( string [ ] args ) { int [ ] arr = { 2 , 4 , 1 , 6 , 5 } ; int N = arr . Length ; Console . WriteLine ( minimum_swaps ( arr , N ) ) ; } }