Maximum Swap - Problem
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.
Input & Output
Example 1 — Basic Swap
$
Input:
num = 2736
›
Output:
7632
💡 Note:
Swap the first digit 2 with the last digit 6 to get 6732, but the optimal is swapping 2 with 7 to get 7236, then we see swapping positions 1 and 3 gives 7632 which is maximum.
Example 2 — No Improvement Possible
$
Input:
num = 9973
›
Output:
9973
💡 Note:
The digits are already in optimal order from left to right, no single swap can improve the value.
Example 3 — Single Digit
$
Input:
num = 1
›
Output:
1
💡 Note:
Single digit number cannot be improved by swapping.
Constraints
- 0 ≤ num ≤ 108
Visualization
Tap to expand
Understanding the Visualization
1
Input
Given integer number as sequence of digits
2
Process
Find optimal single swap to maximize value
3
Output
Return maximum possible number after swap
Key Takeaway
🎯 Key Insight: Use greedy approach to find the leftmost position that can be improved by swapping with the rightmost occurrence of a larger digit
💡
Explanation
AI Ready
💡 Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code