Skip to content

Commit 1f6facd

Browse files
committed
Sync LeetCode submission Runtime - 0 ms (100.00%), Memory - 17.7 MB (77.64%)
1 parent 86c3181 commit 1f6facd

File tree

2 files changed

+60
-0
lines changed

2 files changed

+60
-0
lines changed
Lines changed: 40 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,40 @@
1+
<p>You are given an integer <code>num</code>. You know that Bob will sneakily <strong>remap</strong> one of the <code>10</code> possible digits (<code>0</code> to <code>9</code>) to another digit.</p>
2+
3+
<p>Return <em>the difference between the maximum and minimum&nbsp;values Bob can make by remapping&nbsp;<strong>exactly</strong> <strong>one</strong> digit in </em><code>num</code>.</p>
4+
5+
<p><strong>Notes:</strong></p>
6+
7+
<ul>
8+
<li>When Bob remaps a digit <font face="monospace">d1</font>&nbsp;to another digit <font face="monospace">d2</font>, Bob replaces all occurrences of <code>d1</code>&nbsp;in <code>num</code>&nbsp;with <code>d2</code>.</li>
9+
<li>Bob can remap a digit to itself, in which case <code>num</code>&nbsp;does not change.</li>
10+
<li>Bob can remap different digits for obtaining minimum and maximum values respectively.</li>
11+
<li>The resulting number after remapping can contain leading zeroes.</li>
12+
</ul>
13+
14+
<p>&nbsp;</p>
15+
<p><strong>Example 1:</strong></p>
16+
17+
<pre>
18+
<strong>Input:</strong> num = 11891
19+
<strong>Output:</strong> 99009
20+
<strong>Explanation:</strong>
21+
To achieve the maximum value, Bob can remap the digit 1 to the digit 9 to yield 99899.
22+
To achieve the minimum value, Bob can remap the digit 1 to the digit 0, yielding 890.
23+
The difference between these two numbers is 99009.
24+
</pre>
25+
26+
<p><strong>Example 2:</strong></p>
27+
28+
<pre>
29+
<strong>Input:</strong> num = 90
30+
<strong>Output:</strong> 99
31+
<strong>Explanation:</strong>
32+
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).
33+
Thus, we return 99.</pre>
34+
35+
<p>&nbsp;</p>
36+
<p><strong>Constraints:</strong></p>
37+
38+
<ul>
39+
<li><code>1 &lt;= num &lt;= 10<sup>8</sup></code></li>
40+
</ul>
Lines changed: 20 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,20 @@
1+
# Approach 1: Greedy
2+
3+
# Time: O(log(num))
4+
# Space: O(log(num))
5+
6+
class Solution:
7+
def minMaxDifference(self, num: int) -> int:
8+
s = str(num)
9+
t = s
10+
pos = 0
11+
12+
while pos < len(s) and s[pos] == '9':
13+
pos += 1
14+
if pos < len(s):
15+
s = s.replace(s[pos], '9')
16+
17+
t = t.replace(t[0], '0')
18+
19+
return int(s) - int(t)
20+

0 commit comments

Comments
 (0)