Maximum Difference by Remapping a Digit — LeetCode 2566 Python Solution
EasyGreedyMath
- Problem
- #2566
- Pattern
- Greedy
- Reading time
- 2 min
- Source
- leetcode.com
The problem
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.
Example
- Input
- num = 11891
- Output
- 99009
- Explanation
- To achieve the maximum value, Bob can remap the digit 1 to the digit 9 to yield 99899.
Python solution
Python
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 - miComplexity
| Measure | Complexity |
|---|---|
| Time | O(\log n) |
| Space | O(\log n) auxiliary |
Pattern: Greedy
Take the locally best option every time — when you can prove that never costs you later. LeetCode 2566. Maximum Difference by Remapping a Digit is filed here on both counts: the reference solution below belongs to the algorithm family this hub collects, and LeetCode tags it Greedy.
The greedy guide has the Python template for the pattern and the 346 LeetCode problems that use it.
Related problems
Frequently asked questions
- How hard is LeetCode 2566. Maximum Difference by Remapping a Digit?
- LeetCode 2566. Maximum Difference by Remapping a Digit is rated Easy on LeetCode.
- What is the time complexity of LeetCode 2566. Maximum Difference by Remapping a Digit?
- The Python solution on this page runs in O(\log n).
- What is the space complexity of LeetCode 2566. Maximum Difference by Remapping a Digit?
- The Python solution on this page uses O(\log n) auxiliary space.
- What topics does LeetCode 2566. Maximum Difference by Remapping a Digit cover?
- LeetCode 2566. Maximum Difference by Remapping a Digit is tagged Greedy and Math on LeetCode.