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 Code
< ? php function largestNumber ( $ num ) { $ n = strlen ( $ num ) ; $ rightMax [ $ n ] = array ( 0 ) ; $ right ; $ rightMax [ $ n - 1 ] = -1 ; $ right = $ n - 1 ; for ( $ i = $ n - 2 ; $ i >= 0 ; $ i -- ) { if ( $ num [ $ i ] < $ num [ $ right ] ) $ rightMax [ $ i ] = $ right ; else { $ rightMax [ $ i ] = -1 ; $ right = $ i ; } } for ( $ i = 0 ; $ i < $ n ; $ i ++ ) { if ( $ rightMax [ $ i ] != -1 ) { list ( $ num [ $ i ] , $ num [ $ rightMax [ $ i ] ] ) = array ( $ num [ $ rightMax [ $ i ] ] , $ num [ $ i ] ) ; break ; } } return $ num ; } $ num = "8725634" ; echo " Largest ▁ number : ▁ " , largestNumber ( $ num ) ; ? >