Lexicographically largest permutation by sequentially inserting Array elements at ends | Function to find the lexicographically largest permutation by sequentially inserting the array elements ; Stores the current state of the new array ; Stores ythe current maximum element of array arr [ ] ; Iterate the array elements ; If the current element is smaller than the current maximum , then insert ; If the current element is at least the current maximum ; Update the value of the current maximum ; Prlet resultant permutation ; Driver Code
function largestPermutation ( arr , N ) { let p = [ ] ; let mx = arr [ 0 ] ; p . push ( arr [ 0 ] ) ; for ( let i = 1 ; i < N ; i ++ ) { if ( arr [ i ] < mx ) p . push ( arr [ i ] ) ; else { p . unshift ( arr [ i ] ) ; mx = arr [ i ] ; } } for ( i of p ) document . write ( i + " " ) ; } let arr = [ 3 , 1 , 2 , 4 ] ; let N = arr . length ; largestPermutation ( arr , N ) ;