Maximum Difference by Remapping a Digit Problem
#2566
Try it yourself first
Five languages, sample and hidden tests, right in the browser.
Practice it as an interview
Talk through your solution with an AI interviewer while you code.
Description
LeetCode Problem 2566.
You are given an integer num. You know that Bob will sneakily remap one of the 10 possible digits (0 to 9) to another digit.
Return the difference between the maximum and minimum values Bob can make by remapping exactly one digit in num.
Notes:
- When Bob remaps a digit d1 to another digit d2, Bob replaces all occurrences of
d1innumwithd2. - Bob can remap a digit to itself, in which case
numdoes not change. - Bob can remap different digits for obtaining minimum and maximum values respectively.
- The resulting number after remapping can contain leading zeroes.
Example 1:
Input: num = 11891
Output: 99009
Explanation:
To achieve the maximum value, Bob can remap the digit 1 to the digit 9 to yield 99899.
To achieve the minimum value, Bob can remap the digit 1 to the digit 0, yielding 890.
The difference between these two numbers is 99009.
Example 2:
Input: num = 90
Output: 99
Explanation:
The maximum value that can be returned by the function is 99 (if 0 is replaced by 9) and the minimum value that can be returned by the function is 0 (if 9 is replaced by 0).
Thus, we return 99.
Constraints:
1 <= num <= 10^8
Solution
Approach: Greedy
Work with the digits of num as a string s.
For the minimum, remap the first digit s[0] to 0: that makes the leading digits as small as possible. For the maximum, remap the first digit that is not 9 to 9; if every digit is already 9, the number itself is the maximum. Return the difference.
Complexity: time O(log n), space O(log n), where n is the value of num.
class Solution:
def minMaxDifference(self, num: int) -> int:
s = str(num)
mi = int(s.replace(s[0], '0'))
for c in s:
if c != '9':
return int(s.replace(c, '9')) - mi
return num - mi