| 1 | class Solution { |
| 2 | public int maximumSwap(int num) { |
| 3 | char numArr[] = Integer.toString(num).toCharArray(); |
| 4 | int n = numArr.length; |
| 5 | char maxElement = numArr[n-1]; |
| 6 | int maxIndex = n-1; |
| 7 | int swapIdx1 = -1; |
| 8 | int swapIdx2 = -1; |
| 9 | for(int i=n-2;i>=0;i--){ |
| 10 | if(numArr[i] > maxElement){ |
| 11 | maxElement = numArr[i]; |
| 12 | maxIndex = i; |
| 13 | }else if(numArr[i] < maxElement){ |
| 14 | swapIdx1 = i; |
| 15 | swapIdx2 = maxIndex; |
| 16 | } |
| 17 | } |
| 18 | |
| 19 | //perform swapping |
| 20 | if(swapIdx1!=-1){ |
| 21 | char temp = numArr[swapIdx1]; |
| 22 | numArr[swapIdx1] = numArr[swapIdx2]; |
| 23 | numArr[swapIdx2] = temp; |
| 24 | } |
| 25 | return Integer.parseInt(new String(numArr)); |
| 26 | |
| 27 | } |
| 28 | } |
nothing calls this directly
no outgoing calls
no test coverage detected