Leetcode 2566. Maximum Difference by Remapping a Digit
You are given an integer num
consisting of exactly four digits. You need to find and return the maximum possible difference you can achieve by remapping exactly one digit (0-9) to another digit (0-9). Remapping a digit means replacing all occurrences of it in the number with the new digit.
num
be negative, or is it guaranteed to be a positive four-digit integer?
To solve the problem optimally:
Here is a simple and efficient approach implemented in Java:
public class MaximumDifferenceByRemappingDigit {
public static int minMaxDifference(int num) {
String numStr = Integer.toString(num);
int maxDifference = Integer.MIN_VALUE;
for (char c = '0'; c <= '9'; c++) {
// Skip digit if it is not in the number
if (numStr.indexOf(c) == -1) continue;
// Perform remapping for max
String maxStr = numStr.replace(c, '9');
int maxVal = Integer.parseInt(maxStr);
// Perform remapping for min
String minStr = numStr.replace(c, '0');
int minVal = Integer.parseInt(minStr);
// Calculate difference
int currentDifference = maxVal - minVal;
// update maxDifference
maxDifference = Math.max(maxDifference, currentDifference);
}
return maxDifference;
}
public static void main(String[] args) {
System.out.println(minMaxDifference(1234)); // Example test case, should output the max difference
}
}
O((D * N))
D
is the number of digits (0-9) to potentially remap. Since it’s always 10, it’s a constant factor.N
is the number of digits in the number, which is 4 in this case.O(4 * 10)
, which simplifies to O(1)
as both factors are constants.This approach efficiently finds the maximum possible difference by systematically remapping each digit and considering all valid new values.
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?