[LeetCode] 670. Maximum Swap

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, 108]

Thought process:
Iterate through the digits from left to right. For each digit, iterate through the digits to its right. Try swap every digit that's larger than current digit.
  1. If there is a larger number after the swap, return the largest.
  2. Otherwise, continue to the next digit.

Solution:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
class Solution {
    public int maximumSwap(int num) {
        String s = Integer.toString(num);
        int len = s.length();
        int max = num;
        
        for (int i = 0; i < len; i++) {
            int i1 = s.charAt(i) - '0';
            int p1 = (int) Math.pow(10, len - i - 1);
            
            for (int j = i + 1; j < len; j++) {
                int i2 = s.charAt(j) - '0';
                int p2 = (int) Math.pow(10, len - j - 1);
                max = Math.max(max, num - i1 * p1 + i1 * p2 - i2 * p2 + i2 * p1);
            }
            
            if (max > num) {
                return max;
            }
        }
        return num;
    }
}

Time complexity:
O(n^2) where n = number of digits.

Comments

Popular posts from this blog

[LeetCode] 714. Best Time to Buy and Sell Stock with Transaction Fee

[LeetCode] 269. Alien Dictionary

[LeetCode] 631. Design Excel Sum Formula