Form the largest number using at most one swap operation | C # 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
using System ; using System . Text ; 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 [ i ] < num [ 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 [ i ] = num [ j ] ; sb [ j ] = num [ i ] ; return sb . ToString ( ) ; } public static void Main ( ) { String num = "8725634" ; Console . WriteLine ( " Largest ▁ Number ▁ : ▁ " + largestNumber ( num ) ) ; } }