Form the largest number using at most one swap operation | Java implementation to form the largest number by applying atmost 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 . charAt ( i ) ' is less than the greatest digit encountered so far ; there is no greater right digit for ' num . charAt ( 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 ; Utility method to swap two characters in a String ; Driver Function to test above Function
public class GFG { static String largestNumber ( String num ) { int n = num . length ( ) ; int right ; int rightMax [ ] = new int [ n ] ; rightMax [ n - 1 ] = - 1 ; right = n - 1 ; for ( int i = n - 1 ; i >= 0 ; i -- ) { if ( num . charAt ( i ) < num . charAt ( right ) ) rightMax [ i ] = right ; else { rightMax [ i ] = - 1 ; right = i ; } } for ( int i = 0 ; i < n ; i ++ ) { if ( rightMax [ i ] != - 1 ) { num = swap ( num , i , rightMax [ i ] ) ; break ; } } return num ; } static String swap ( String num , int i , int j ) { StringBuilder sb = new StringBuilder ( num ) ; sb . setCharAt ( i , num . charAt ( j ) ) ; sb . setCharAt ( j , num . charAt ( i ) ) ; return sb . toString ( ) ; } public static void main ( String [ ] args ) { String num = "8725634" ; System . out . println ( " Largest ▁ Number ▁ : ▁ " + largestNumber ( num ) ) ; } }