-
Notifications
You must be signed in to change notification settings - Fork 13
/
solution.java
30 lines (27 loc) · 1007 Bytes
/
solution.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
class Solution {
public int maximumSwap(int num) {
// Convert number to string for digit manipulation
char[] numArr = Integer.toString(num).toCharArray();
int n = numArr.length;
// Track the last occurrence of each digit (0-9)
int[] last = new int[10];
for (int i = 0; i < n; i++) {
last[numArr[i] - '0'] = i;
}
// Traverse the number from left to right
for (int i = 0; i < n; i++) {
// Check if we can find a larger digit to swap
for (int d = 9; d > numArr[i] - '0'; d--) {
if (last[d] > i) {
// Swap and return the new number
char temp = numArr[i];
numArr[i] = numArr[last[d]];
numArr[last[d]] = temp;
return Integer.parseInt(new String(numArr));
}
}
}
// Return the original number if no swap occurred
return num;
}
}