Maximum Difference by Remapping a Digit — LeetCode 2566 Python Solution

EasyGreedyMath
Problem
#2566
Pattern
Greedy
Reading time
2 min

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 - mi

Complexity

MeasureComplexity
TimeO(\log n)
SpaceO(\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.

Stuck on problems like this in a live interview?

Stealth Interview is a desktop app for macOS and Windows. It reads the problem off your screen and returns a working solution with a step-by-step explanation and its time and space complexity — invisible to screen sharing.

Get Stealth Interview