text: Largest smaller number possible using only one swap operation | C # program to find the largest smaller number by swapping one digit . ; Returns largest possible number with one swap such that the number is smaller than str . It is assumed that there are leading 0 s . ; Traverse from right until we find a digit which is greater than its next digit . For example , in 34125 , our index is 4. ; We can also use binary search here as digits after index are sorted in increasing order . Find the biggest digit in the right of arr [ index ] which is smaller than arr [ index ] ; If index is - 1 i . e . digits are in increasing order . ; Swap both values ; Driver code
code: using System ; class GFG { static String prevNum ( String str ) { int len = str . Length ; int index = - 1 ; for ( int i = len - 2 ; i >= 0 ; i -- ) { if ( str [ i ] > str [ i + 1 ] ) { index = i ; break ; } } int smallGreatDgt = - 1 ; for ( int i = len - 1 ; i > index ; i -- ) { if ( str [ i ] < str [ index ] ) { if ( smallGreatDgt == - 1 ) { smallGreatDgt = i ; } else if ( str [ i ] >= str [ smallGreatDgt ] ) { smallGreatDgt = i ; } } } if ( index == - 1 ) { return " - 1" ; } if ( smallGreatDgt != - 1 ) { str = swap ( str , index , smallGreatDgt ) ; return str ; } return " - 1" ; } static String swap ( String str , int i , int j ) { char [ ] ch = str . ToCharArray ( ) ; char temp = ch [ i ] ; ch [ i ] = ch [ j ] ; ch [ j ] = temp ; return String . Join ( " " , ch ) ; } public static void Main ( String [ ] args ) { String str = "34125" ; Console . WriteLine ( prevNum ( str ) ) ; } }