Maximum Swap - Complete Solution Guide
Maximum Swap is LeetCode problem 670, a Medium level challenge. This complete guide provides step-by-step explanations, multiple solution approaches, and optimized code in python3, java, cpp, c.
Problem Statement
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: 0 <= num <= 10 8
Detailed Explanation
The problem asks us to find the maximum possible integer that can be obtained from a given integer `num` by swapping two of its digits at most once. If no swap results in a larger number, we return the original number. The input `num` is constrained to be between 0 and 10^8.
Solution Approach
The solution involves first converting the integer into a string (or char array). Then, it creates a data structure (HashMap or array) to store the last occurrence of each digit in the number. After that, it iterates through the string from left to right. For each digit, it checks if there's a larger digit occurring later in the number. If such a digit is found, it performs the swap and returns the resulting integer. If no such digit is found after iterating through the entire number, it means the number is already the largest possible, so it returns the original number.
Step-by-Step Algorithm
- Step 1: Convert the integer `num` to a string or character array.
- Step 2: Create a data structure (HashMap/array) to store the last index (rightmost occurrence) of each digit in the string.
- Step 3: Iterate through the string from left to right (index `i`).
- Step 4: For each digit at index `i`, iterate from '9' to `s_list[i]` to find a larger digit.
- Step 5: If a larger digit `d_char` is found, check if it exists in the last occurrence map and if its last occurrence index `j` is greater than `i`. This ensures the larger digit is to the right of the current digit.
- Step 6: If a suitable larger digit is found, swap the digits at indices `i` and `j`.
- Step 7: Convert the modified string back to an integer and return it.
- Step 8: If the loop completes without finding a suitable swap, return the original number.
Key Insights
- Insight 1: To maximize the number, we need to find the leftmost digit that can be swapped with a larger digit to its right.
- Insight 2: We need to efficiently track the last occurrence of each digit in the number to find the best candidate for the swap.
- Insight 3: If the digits are already in descending order from left to right, no swap is necessary.
Complexity Analysis
Time Complexity: O(N)
Space Complexity: O(1)
Topics
This problem involves: Math, Greedy.
Companies
Asked at: KLA.