Lexicographically largest permutation possible by a swap that is smaller than a given array | 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 ; Pr the array arr [ ] ; Driver Code
def findPermutation ( arr ) : NEW_LINE INDENT N = len ( arr ) NEW_LINE i = N - 2 NEW_LINE while ( i >= 0 and arr [ i ] <= arr [ i + 1 ] ) : NEW_LINE INDENT i -= 1 NEW_LINE DEDENT if ( i == - 1 ) : NEW_LINE INDENT print ( " - 1" ) NEW_LINE return NEW_LINE DEDENT j = N - 1 NEW_LINE while ( j > i and arr [ j ] >= arr [ i ] ) : NEW_LINE INDENT j -= 1 NEW_LINE DEDENT while ( j > i and arr [ j ] == arr [ j - 1 ] ) : NEW_LINE INDENT j -= 1 NEW_LINE DEDENT temp = arr [ i ] ; NEW_LINE arr [ i ] = arr [ j ] ; NEW_LINE arr [ j ] = temp ; NEW_LINE for it in arr : NEW_LINE INDENT print ( it , end = " ▁ " ) NEW_LINE DEDENT DEDENT arr = [ 1 , 2 , 5 , 3 , 4 , 6 ] NEW_LINE findPermutation ( arr ) NEW_LINE