#2566
Maximum Difference by Remapping a Digit
EasyMathGreedyGreedyString Manipulation
Approaches
Brute ForceOptimal
Complexity Comparison
| Brute Force | Optimal Solution★ | |
|---|---|---|
| Time | O(n²) | O(n) |
| Space | O(1) | O(n) |
💡
Intuition
Time O(n)Space O(n)
The optimal solution focuses on strategically remapping the first non-nine digit to 9 for the maximum value and the first non-zero digit to 0 for the minimum value. This reduces unnecessary computations and directly targets the digits that will yield the largest difference.
⚙️
Algorithm
4 steps- 1Step 1: Convert the number to a string to access each digit.
- 2Step 2: Identify the first non-nine digit and replace it with 9 to get the maximum value.
- 3Step 3: Identify the first non-zero digit and replace it with 0 to get the minimum value.
- 4Step 4: Return the difference between the maximum and minimum values.
solution.py15 lines
1# Full working Python code
2
3def maxDifference(num):
4 num_str = str(num)
5 max_num = num_str
6 min_num = num_str
7 for i in range(len(num_str)):
8 if num_str[i] != '9':
9 max_num = num_str[:i] + '9' + num_str[i+1:]
10 break
11 for i in range(len(num_str)):
12 if num_str[i] != '0':
13 min_num = num_str[:i] + '0' + num_str[i+1:]
14 break
15 return int(max_num) - int(min_num)ℹ
Complexity note: The complexity is O(n) because we are only iterating through the digits of the number a couple of times, which is linear with respect to the number of digits.
- 1The first non-nine digit should be replaced with 9 for maximum value.
- 2The first non-zero digit should be replaced with 0 for minimum value.
Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.