670. Maximum Swap
You are given an integer num. You can swap two digits at most once to get the maximum valued number.
Return the maximum valued number you can get.
Example 1:
Input: num = 2736
Output: 7236
Explanation: Swap the number 2 and the number 7.
Example 2:
Input: num = 9973
Output: 9973
Explanation: No swap.
Constraints:
- 0 < = n u m < = 1 0 8 0 <= num <= 10^8 0<=num<=108
From: LeetCode
Link: 670. Maximum Swap
Solution:
Ideas:
-
We first convert the number into an array of digits.
-
Then we keep track of the last occurrence of each digit.
-
We scan from left to right, and for each digit, check if there is a larger digit later. If so, we swap them to maximize the number.
-
Only one swap is allowed, so we return the number right after the swap.
Code:
int maximumSwap(int num) {
// Convert number to array of digits
int digits[10];
int len = 0, temp = num;
while (temp > 0) {
digits[len++] = temp % 10;
temp /= 10;
}
if (len == 0) return 0;
// Reverse the digits to get the correct order
for (int i = 0; i < len / 2; i++) {
int t = digits[i];
digits[i] = digits[len - 1 - i];
digits[len - 1 - i] = t;
}
// Record the last position of each digit
int last[10];
for (int i = 0; i < 10; i++) last[i] = -1;
for (int i = 0; i < len; i++) {
last[digits[i]] = i;
}
// Try to find the first place where a bigger digit can be swapped
for (int i = 0; i < len; i++) {
for (int d = 9; d > digits[i]; d--) {
if (last[d] > i) {
// Perform swap
int t = digits[i];
digits[i] = digits[last[d]];
digits[last[d]] = t;
// Convert back to number
int result = 0;
for (int j = 0; j < len; j++) {
result = result * 10 + digits[j];
}
return result;
}
}
}
// If no swap needed
return num;
}