Maximum Swap

Description

Given a non-negative integer, you could swap two digits at most once to get the maximum valued number. Return the maximum valued number you could get.

Example 1:

Input: 2736
Output: 7236
Explanation: Swap the number 2 and the number 7.

Example 2:

Input: 9973
Output: 9973
Explanation: No swap.

Note:

  1. The given number is in the range [0, 10810^8 ]

Solutions

My solution

Algorithm:

  1. Let num[i] denote the ithi^{th} digit.

  2. Set i = 0.

  3. While num[i] is larger than any digit after it, ++i.

  4. Find the largest digit after num[i], say num[j] (if there are multiple largest digits, use the last one). Then swap num[i] and num[j].

A better solution

Same idea, but better implementation. The key is to store only the last occurrence of i,i[0,9]i, \forall i \in [0, 9].

Credit: Java simple solution, O(n) time

Last updated