text: Lexicographically largest permutation possible by a swap that is smaller than a given array | C ++ program for the above approach ; Function to lexicographic largest permutation possible by a swap that is smaller than given array ; Find the index of first element such that arr [ i ] > arr [ i + 1 ] ; If the array is sorted in increasing order ; Find the index of first element which is smaller than arr [ i ] ; If arr [ j ] = = arr [ j - 1 ] ; Decrement j ; Swap the element ; Print the array arr [ ] ; Driver Code
code: #include <bits/stdc++.h> NEW_LINE using namespace std ; void findPermutation ( vector < int > & arr ) { int N = arr . size ( ) ; int i = N - 2 ; while ( i >= 0 && arr [ i ] <= arr [ i + 1 ] ) i -- ; if ( i == -1 ) { cout << " - 1" ; return ; } int j = N - 1 ; while ( j > i && arr [ j ] >= arr [ i ] ) j -- ; while ( j > i && arr [ j ] == arr [ j - 1 ] ) { j -- ; } swap ( arr [ i ] , arr [ j ] ) ; for ( auto & it : arr ) { cout << it << ' ▁ ' ; } } int main ( ) { vector < int > arr = { 1 , 2 , 5 , 3 , 4 , 6 } ; findPermutation ( arr ) ; return 0 ; }