Maximum Swap
Example
Input: 2736
Output: 7236
Explanation: Swap the number 2 and the number 7.Input: 9973
Output: 9973
Explanation: No swap.Note
Code
Last updated
Input: 2736
Output: 7236
Explanation: Swap the number 2 and the number 7.Input: 9973
Output: 9973
Explanation: No swap.Last updated
class Solution {
public int maximumSwap(int num) {
String s = String.valueOf(num);
char[] c = s.toCharArray();
int len = c.length;
int left = -1, right = -1;
int max = -1, index = -1;
for (int i = len - 1; i >= 0; i--) {
if (c[i] > max) {
index = i;
max = c[i];
continue;
}
if (c[i] < max) {
left = i;
right = index;
}
}
System.out.println(right + " " + left);
if (left == -1) {
return num;
}
char temp = c[left];
c[left] = c[right];
c[right] = temp;
return Integer.parseInt(String.valueOf(c));
}
}