Maximum Swap Problem


Description

LeetCode Problem 670.

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.

Example 1:

1
2
3
Input: num = 2736
Output: 7236
Explanation: Swap the number 2 and the number 7.

Example 2:

1
2
3
Input: num = 9973
Output: 9973
Explanation: No swap.

Constraints:

  • 0 <= num <= 10^8


Sample C++ Code

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
class Solution {
public:
    int maximumSwap(int num) {
        string n = to_string(num);
        
        // Keep in a map the last accurance of each digit:
        unordered_map<int, int> last;
        for (int i = 0; i < n.size(); i++)
            last[n[i] - '0'] = i;
        
        for (int i = 0; i < n.size(); i++) {
            for (int j = 9; j > n[i]-'0'; j--) {
                // If there's a larger digit later - swap:
                if (last[j] > i) {
                    swap(n[last[j]], n[i]);
                    return stoi(n);
                }
            }
        }
        return stoi(n);
    }
};




Related Posts

Lemonade Change Problem

LeetCode 860. At a lemonade stand, each lemonade costs $5....

Set Intersection Size At Least Two Problem

LeetCode 757. You are given a 2D integer array intervals...

Maximum Swap Problem

LeetCode 670. You are given an integer num. You can...

Can Place Flowers Problem

LeetCode 605. You have a long flowerbed in which some...

Super Washing Machines Problem

LeetCode 517. You have n super washing machines on a...

Minimum Number Of Arrows To Burst Balloons Problem

LeetCode 452. There are some spherical balloons taped onto a...