The Maximum Swap problem involves finding the largest number possible by swapping two digits in a given non-negative integer. You can perform at most one swap.
class Solution {
public int maximumSwap(int num) {
char[] digits = Integer.toString(num).toCharArray();
int n = digits.length;
// Track the maximum digit and its index from the right
int maxIdx = n - 1;
int leftIdx = -1, rightIdx = -1;
// Traverse the digits from right to left
for (int i = n - 2; i >= 0; i--) {
if (digits[i] > digits[maxIdx]) {
maxIdx = i; // Update the max index
} else if (digits[i] < digits[maxIdx]) {
// Found a potential swap
leftIdx = i;
rightIdx = maxIdx;
}
}
// If a swap is possible, perform it
if (leftIdx != -1) {
char temp = digits[leftIdx];
digits[leftIdx] = digits[rightIdx];
digits[rightIdx] = temp;
}
// Return the result as an integer
return Integer.parseInt(new String(digits));
}
}
For a detailed explanation, watch this video: Maximum Swap Problem Explanation by NeetCode IO
O(N)
, where N
is the number of digits in the input number.O(1)
, as we use only a constant amount of extra space.Input: num = 2736
Output: 7236
Explanation:
- Swap the digits 2 and 7 to get the largest number 7236.