-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathMed670.java
32 lines (27 loc) · 943 Bytes
/
Med670.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
//maximum swap
class Med670 {
public int maximumSwap(int num) {
char numArr[] = Integer.toString(num).toCharArray();
int n = numArr.length;
char maxElement = numArr[n-1];
int maxIndex = n-1;
int swapIdx1 = -1;
int swapIdx2 = -1;
for(int i=n-2;i>=0;i--){
if(numArr[i] > maxElement){
maxElement = numArr[i];
maxIndex = i;
}else if(numArr[i] < maxElement){
swapIdx1 = i;
swapIdx2 = maxIndex;
}
}
//perform swapping
if(swapIdx1!=-1){
char temp = numArr[swapIdx1];
numArr[swapIdx1] = numArr[swapIdx2];
numArr[swapIdx2] = temp;
}
return Integer.parseInt(new String(numArr));
}
}