451/670

451. Maximum Swap

Medium

You get a non-negative integer num. You may choose two positions in its decimal representation and swap those digits — at most once (doing nothing is allowed).

Return the largest value you can produce.

The function receives the integer and returns an integer.

Example 1:

Input: num = 2736

Output: 7236

Explanation: Swapping the 2 and the 7 puts the biggest available digit in the most significant slot: 2736 becomes 7236. No other single swap beats it.

Example 2:

Input: num = 9973

Output: 9973

Explanation: The digits already read in non-increasing order, so every swap makes the number smaller or equal. The best move is no move.

Constraints:

  • 0 ≤ num ≤ 10⁸

Hints:

A swap helps only if some digit later in the number is strictly bigger than a digit earlier. To maximize the result, fix the leftmost position that can be improved — improving a more significant digit always beats improving a less significant one.

For that position you want the biggest later digit — and among equal candidates, the rightmost one. Swapping 1993's 1 with the second 9 gives 9913; with the first 9 only 9193. Precompute the last index where each digit 0–9 occurs.

▶ Run checks these sample cases. Submit also runs hidden edge cases.

Input: num = 2736

Expected output: 7236