Max Difference You Can Get From Changing an Integer Problem
Description
LeetCode Problem 1432.
You are given an integer num. You will apply the following steps to num two separate times:
- Pick a digit
x (0 <= x <= 9). - Pick another digit
y (0 <= y <= 9). Noteycan be equal tox. - Replace all the occurrences of
xin the decimal representation ofnumbyy.
Let a and b be the two results from applying the operation to num independently.
Return the max difference between a and b.
Note that neither a nor b may have any leading zeros, and must not be 0.
Example 1:
Input: num = 555
Output: 888
Explanation: The first time pick x = 5 and y = 9 and store the new integer in a.
The second time pick x = 5 and y = 1 and store the new integer in b.
We have now a = 999 and b = 111 and max difference = 888
Example 2:
Input: num = 9
Output: 8
Explanation: The first time pick x = 9 and y = 9 and store the new integer in a.
The second time pick x = 9 and y = 1 and store the new integer in b.
We have now a = 9 and b = 1 and max difference = 8
Constraints:
1 <= num <= 10^8
Solution
Approach: Greedy, Largest Minus Smallest
The two operations are independent, so the best difference is simply the largest number a we can make minus the smallest number b we can make.
Largest: a number gets bigger most by raising its highest digit. Find the first digit from the left that is not 9 and replace all of its occurrences with 9. If every digit is already 9, keep the number.
Smallest: the leading digit can not become 0, so:
- If the leading digit is not
1, replace all of its occurrences with1. This lowers the highest position, which beats anything else. - If it is already
1, keep it and find the first later digit that is neither0nor1, then replace all of its occurrences with0. We skip1s because turning them into0would also turn the leading1into0.
For example, num = 1101057: the first digit is 1, the first later digit that is not 0 or 1 is 5, so b = 1101007, and a = 9909057.
Complexity: O(d) time and space, where d ≤ 9 is the number of digits.
class Solution:
def maxDiff(self, num: int) -> int:
s = str(num)
# largest: turn the first digit that is not 9 into 9, everywhere
a = s
for c in s:
if c != "9":
a = s.replace(c, "9")
break
# smallest: the leading digit can go down to 1 but never to 0
b = s
if s[0] != "1":
b = s.replace(s[0], "1")
else:
# the leading 1 stays, so turn the first later digit that is not 0 or 1 into 0
for c in s[1:]:
if c not in "01":
b = s.replace(c, "0")
break
return int(a) - int(b)