670. Maximum Swap
You are given a non-negative 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 digit 2 with the digit 7.
Example 2:
Input: num = 9973
Output: 9973
Explanation: No swap needed because the number is already the largest possible.
Constraints:
0 <= num <= 10^8
Here’s the implementation of the above strategy:
public class Solution {
public int maximumSwap(int num) {
char[] digits = Integer.toString(num).toCharArray();
int n = digits.length;
// Record the last seen position of digit 0-9
int[] last = new int[10];
for (int i = 0; i < n; i++) {
last[digits[i] - '0'] = i;
}
// Try to find the first place to make a swap to get a bigger number
for (int i = 0; i < n; i++) {
for (int d = 9; d > digits[i] - '0'; d--) {
if (last[d] > i) {
// Swap digits[i] and digits[last[d]]
char temp = digits[i];
digits[i] = digits[last[d]];
digits[last[d]] = temp;
// Convert the array back to integer and return
return Integer.parseInt(new String(digits));
}
}
}
return num; // No swap makes the number larger
}
}
O(n)
where n
is the number of digits.O(10 * n)
, but since the inner loop runs at most 10 times, it simplifies to O(n)
overall.O(n)
.O(n)
due to the array creation which holds the digit characters and auxiliary space for the last
array.This strategy ensures that we identify the optimal digits to swap in a single pass, making the solution efficient and straightforward.
Got blindsided by a question you didn’t expect?
Spend too much time studying?
Or simply don’t have the time to go over all 3000 questions?