# Maximum Swap

• Even though it is O(n), it is in fact 9n. We can simply solve this problem by two passes.

• I have a very simple easy-to-understand solution (C++) to share: one single scan from backward without any embedded loop.
During the scan, if the current digit is the largest by far, record it and its index; or if the current digit is smaller than the largest digit recorded by far, this digit and the largest digit are the best candidate for max swap.
https://discuss.leetcode.com/topic/105218/c-one-pass-simple-fast-solution-1-3ms-o-n-time

• Hows my solution looking btw?

class Solution {
/*
https://leetcode.com/submissions/detail/127441090/
*/
public int maximumSwap(int num) {

``````	char[] numCharArr = String.valueOf(num).toCharArray();
//int[] values = { 0, 0 };
int index1 = 0;
int index2 =0;
int value = 0;
boolean haslarger = false;
for (int i = 0; i < numCharArr.length; i++) {
int currentnum = Integer.valueOf(numCharArr[i]);
if ( haslarger ) {
char temp = numCharArr[index1];
numCharArr[index1] = numCharArr[index2];
numCharArr[index2] = temp;
return Integer.valueOf(new String(numCharArr));
}
for (int j = i + 1; j < numCharArr.length; j++) {
int valueForCompare = Integer.valueOf(numCharArr[j]);

if (currentnum < valueForCompare) {
haslarger =true;

if (value <= valueForCompare) {
index1 = i;
index2 = j;
value = valueForCompare;
}

}

}
}

return num;

}
``````

}

• Will following solution work?

1. Sort the numbers (in descending order)
2. Pick 1st element and move swap it to the left most element.
3. If 1st element already has max element, follow #2 for 2nd max element

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.