The Indian Engineer

Problem 670 Maximum Swap

Posted on 5 mins

Math Greedy

Problem Statement

Link - Problem 670

Question

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:

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

Example 2:

Input: num = 9973
Output: 9973
Explanation: No swap.

Constraints:

Solution

class Solution {
public:
    int maximumSwap(int num) {
        string numStr = to_string(num);
        int n = numStr.size();
        vector<int> maxRightIndex(n);

        maxRightIndex[n - 1] = n - 1;
        for (int i = n - 2; i >= 0; --i) {
            maxRightIndex[i] = (numStr[i] > numStr[maxRightIndex[i + 1]]) ? i: maxRightIndex[i + 1];
        }

        for (int i = 0; i < n; ++i) {
            if (numStr[i] < numStr[maxRightIndex[i]]) {
                swap(numStr[i],
                     numStr[maxRightIndex[i]]);
                return stoi(numStr);
            }
        }

        return num;
    }
};

Complexity Analysis

| Algorithm                                | Time Complexity | Space Complexity |
| ---------------------------------------- | --------------- | ---------------- |
| Two-pointer traversal with preprocessing | O(n)            | O(n)             |

Explanation

Intial Thoughts

To begin, break down the problem into smaller parts: converting the number to a string to easily access individual digits, then iterating through the digits from right to left to keep track of the maximum digit encountered so far. Consider using a data structure like a vector to store the indices of the maximum digits found so far. Think about how swapping two digits can affect the overall value of the number, focusing on maximizing the leftmost digits first. The goal is to find the first instance from the left where a smaller digit can be swapped with a larger one from the right. Start by considering extreme cases, such as numbers with all identical digits or numbers already in the maximum possible order.

Intuitive Analysis

Intuitively, the solution involves finding the first digit from the left that is smaller than the maximum digit to its right, because this is where swapping will have the greatest impact on the number’s value. Visualize the process as scanning the number from left to right while keeping track of the ‘best’ digit seen so far from the right. At each step, ask whether the current digit is less than the maximum digit found to its right, and if so, whether swapping them increases the number’s value. Consider the trade-offs between the positions of digits and their values, thinking about how moving a larger digit to the left can significantly increase the overall value. This process is akin to a greedy strategy where the goal is to maximize the value by making the optimal choice at each step without worrying about future steps.

1. Intuition

2. Implementation


Complexity Analysis

Time Complexity:

Space Complexity:


Footnote

This question is rated as Medium difficulty.


Similar Questions:

Title URL Difficulty
Create Maximum Number https://leetcode.com/problems/create-maximum-number Hard