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
Maximum Swap Problem OverviewINPUT2736PROCESSFind best single swap:2736swap positions 1↔3OUTPUT7632Original: 2736 → Maximum: 7632One swap can increase 2736 to 7632 (best possible)
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
Asked in
Facebook 25 Google 15
28.0K Views
Medium Frequency
~15 min Avg. Time
892 Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen