Form the largest number using at most one swap operation | function to form the largest number by applying atmost one swap operation ; for the rightmost digit , there will be no greater right digit ; index of the greatest right digit till the current index from the right direction ; traverse the array from second right element up to the left element ; if ' num [ i ] ' is less than the greatest digit encountered so far ; else ; there is no greater right digit for ' num [ i ] ' ; update ' right ' index ; traverse the ' rightMax [ ] ' array from left to right ; if for the current digit , greater right digit exists then swap it with its greater right digit and break ; performing the required swap operation ; required largest number ; Driver program to test above
function largestNumber ( num ) { var n = num . length ; var rightMax = Array ( n ) , right ; rightMax [ n - 1 ] = - 1 ; right = n - 1 ; for ( var i = n - 2 ; i >= 0 ; i -- ) { if ( num [ i ] < num [ right ] ) rightMax [ i ] = right ; else { rightMax [ i ] = - 1 ; right = i ; } } for ( var i = 0 ; i < n ; i ++ ) { if ( rightMax [ i ] != - 1 ) { var tmp = num [ i ] ; num [ i ] = num [ rightMax [ i ] ] ; num [ rightMax [ i ] ] = tmp break ; } } return num . join ( ' ' ) ; } var num = " " . split ( ' ' ) ; document . write ( " " + largestNumber ( num ) ) ;