
Problem Statement
In this task, you are presented with a single integer, num
. You are permitted to make a single operation: swapping any two digits of num
exactly once. Your goal is to transform the initial number into the highest possible numerical value achievable through such a swap. If the number is already the maximum value that can be achieved, no swap is necessary. You need to determine and return this maximum value.
Examples
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 <= 108
Approach and Intuition
To find the most effective strategy for increasing the numerical value of num
through a single swap, here is a general approach:
- Convert the number to a list of digits to easily access and manipulate individual digits.
- Traverse through the digits, and for each digit, determine if a swap with another, later digit will yield a more substantial numerical value.
- Ensure that the number you aim to swap enhances the value of the whole number. Focus essentially on moving higher values to the more significant digit places.
- After examining potential swaps, if no beneficial swap is found, the number should be returned as is because it's already the maximum obtainable.
Begin by converting the integer to a list of its digits. Scan from left to right trying to find the first occurrence where a number can be increased by swapping it with a larger number placed on its right. Keep track of the largest digit seen as you continue scanning to the right. If such a condition is found, perform the swap and construct the large number possible from the new sequence of digits.
This method focuses on a direct search for the ideal swap operation to maximize the number. Since you only need a single swap operation, once a beneficial swap is found, there is no need to continue further checks.
Solutions
- C++
- Java
- Python
class Solution {
public:
int maximumSwap(int num) {
string s = to_string(num);
int length = s.length();
int maxIdx = -1, first = -1, second = -1;
for (int i = length - 1; i >= 0; --i) {
if (maxIdx == -1 || s[i] > s[maxIdx]) {
maxIdx = i;
} else if (s[i] < s[maxIdx]) {
first = i;
second = maxIdx;
}
}
if (first != -1 && second != -1) {
swap(s[first], s[second]);
}
return stoi(s);
}
};
In this C++ solution, determine the maximum number possible by swapping two digits in the given number:
- Convert the integer
num
to its string representation. - Initialize three variables:
maxIdx
to keep track of the index of the current maximum digit found scanning from the end,first
andsecond
as the indices of the digits to potentially swap. - Iterate backwards from the last digit to the first:
- Update
maxIdx
if a new maximum digit is found. - Identify the digits to be swapped, marking
first
with the index of the current digit andsecond
with the index of the current maximum digit.
- Update
- If valid indices are found for
first
andsecond
, perform the swap of these two digits in the string. - Convert the resultant string back to an integer and return.
This approach efficiently identifies the two best digits to swap in order to obtain the maximum number possible, without unnecessary comparisons or temporary arrays. By scanning from the end of the number towards the start, it ensures that the swap makes the result as large as possible with just a single swap operation.
class Solution {
public int maxSwap(int number) {
char[] digits = Integer.toString(number).toCharArray();
int length = digits.length;
int indexMax = -1, firstPosition = -1, secondPosition = -1;
for (int i = length - 1; i >= 0; --i) {
if (indexMax == -1 || digits[i] > digits[indexMax]) {
indexMax = i;
} else if (digits[i] < digits[indexMax]) {
firstPosition = i;
secondPosition = indexMax;
}
}
if (firstPosition != -1 && secondPosition != -1) {
char temporary = digits[firstPosition];
digits[firstPosition] = digits[secondPosition];
digits[secondPosition] = temporary;
}
return Integer.parseInt(new String(digits));
}
}
The given Java code presents a solution for determining the maximum possible value that can be obtained from a number by swapping its digits only once.
- Start by converting the integer to a character array of its digits. This array allows easy swapping and comparison of individual digits.
- Initiate a single pass from the rightmost digit (least significant) to the leftmost digit (most significant). This approach helps to find the maximum digit that appears after each current digit, enabling an identification of the optimal swap position.
- Utilize three variables:
indexMax
to store the index of the maximum digit found so far,firstPosition
for the index where a potential lower digit occurs prior to a maximum digit, andsecondPosition
for the index of that maximum digit which is located to the right of a less significant digit. - As you iterate through the digits, update
indexMax
if a new maximum is found. For any digit that is less than the value atindexMax
, updatefirstPosition
andsecondPosition
. This captures the most last occurrence where the swap would result in a larger number. - If valid positions for a swap are discovered (
firstPosition
andsecondPosition
are not -1), perform the swap in the character array. - Convert the character array back into an integer, and return this integer, which represents the maximum value that can be achieved through a single swap.
By following this algorithm, efficiently achieve the possible maximum value of the number by strategically swapping two digits just once. This ensures the impact of the swap is maximized, considering the positional weight of digits in decimal numeration.
class Solution:
def maximumSwap(self, number: int) -> int:
digits = list(str(number))
length = len(digits)
index_max = -1
swap_a = -1
swap_b = -1
# Iterate over digits from right to left
for i in range(length - 1, -1, -1):
if index_max == -1 or digits[i] > digits[index_max]:
index_max = i
elif digits[i] < digits[index_max]:
swap_a = i
swap_b = index_max
# Execute the digit swap if required
if swap_a != -1 and swap_b != -1:
digits[swap_a], digits[swap_b] = digits[swap_b], digits[swap_a]
return int("".join(digits)) # Convert list of digits back to the integer and return
The provided Python solution aims to solve the problem of maximizing a number by swapping two of its digits once. The approach used in this solution is both effective and efficient, as it scans the digits of the number from right to left, identifying potential swaps that would yield a larger number.
- Initialize
digits
as a list of character strings representing the digits of the input number. - Use three auxiliary variables:
index_max
to track the index of the maximum digit found from right to left,swap_a
, andswap_b
to hold the indices of the digits to be swapped. - Iterate through the digits from right to left:
- Update
index_max
whenever a new maximum digit is encountered. - If a current digit is less than the digit at
index_max
, setswap_a
to the current index andswap_b
toindex_max
.
- Update
- After identifying the right digits to be swapped (if any), execute the swap to form the maximum possible number under the constraints.
- Convert the rearranged list of digits back to an integer and return this as the result.
Implement this code for a swift execution of the strategy to maximize a given number through a single swap operation, ensuring the returned integer is the largest possible result from such a transformation.
No comments yet.