Leetcode 2566. Maximum Difference by Remapping a Digit
You are given an integer num
. You will choose exactly two different digits a
and b
from the decimal representation of num
, and replace all occurrences of the digit a
with b
and all occurrences of the digit b
with a
. Your goal is to maximize the difference between the transformed integer and num
. Return the maximum difference you can achieve.
Input: num = 123456
Output: 619836
Note: For num = 123456
, you can choose a = 1
and b = 6
, then swap them resulting in 623451
. The difference between 623451
and 123456
is 499995
.
To solve this problem, we can follow these steps:
num
into its string representation.a
and b
in the string.a
are replaced with b
and all occurrences of b
are replaced with a
.num
.a
and b
guaranteed to be different digits?
a
and b
must be different digits.num
have leading zeros after digit replacement?
#include <iostream>
#include <string>
#include <vector>
#include <algorithm>
#include <cmath>
int getMaxDifferenceByRemapping(int num) {
std::string numStr = std::to_string(num);
int n = numStr.size();
int maxDifference = 0;
for (char a = '0'; a <= '9'; ++a) {
for (char b = '0'; b <= '9'; ++b) {
if (a != b) {
std::string transformed = numStr;
for (int i = 0; i < n; ++i) {
if (transformed[i] == a) {
transformed[i] = b;
} else if (transformed[i] == b) {
transformed[i] = a;
}
}
int transformedNum = std::stoi(transformed);
int currentDifference = std::abs(transformedNum - num);
maxDifference = std::max(maxDifference, currentDifference);
}
}
}
return maxDifference;
}
int main() {
int num = 123456;
std::cout << "Maximum Difference: " << getMaxDifferenceByRemapping(num) << std::endl;
return 0;
}
The time complexity of this algorithm is O(n * 10 * 10), where:
n
is the number of digits in the integer num
.Thus, the time complexity simplifies to O(n), which is efficient for typical input sizes.
Got blindsided by a question you didn’t expect?
Spend too much time studying?
Or simply don’t have the time to go over all 3000 questions?