Skip to main content
Back to problems
Leetcode
Medium
Math
Greedy
Strings
Maximum Difference By Remapping A Digit

Given a non-negative integer, remap one digit at a time to maximize the difference between the largest and smallest possible values.

Acceptance 100%
Problem Statement

You are given a non-negative integer represented as a decimal number. You may choose a digit and remap every occurrence of that digit to another digit, with the same digit-to-digit replacement applied to all its occurrences.

Your task is to maximize the difference between the largest and smallest numbers you can obtain after performing up to two such remappings independently: one to create the largest possible number and one to create the smallest possible number.

Return that maximum difference.

The remapping rules are applied to the decimal representation only, and leading zeros in the resulting number are allowed during the transformation process, though the final numeric value is interpreted normally.

Input Format

A single integer nn in decimal form.

Output Format

Return the maximum possible difference between the remapped maximum value and remapped minimum value.

Constraints

  • 0n0 \le n
  • The number fits in a 32-bit signed integer in the original LeetCode setting.
  • Remapping replaces all occurrences of one chosen digit with another chosen digit.
Examples
Sample cases returned by the problem API.

Example 1

Input

n = 11891

Output

99009

Explanation

One optimal maximum remapping is to change digit 1 to 9, giving 99899. One optimal minimum remapping is to change digit 1 to 0, giving 00890 which is interpreted as 890. The difference is 99899 - 890 = 99009.

Example 2

Input

n = 90

Output

99

Explanation

The maximum value is already 99 after remapping 0 to 9, while the minimum value is 0 by remapping 9 to 0. The difference is 99.

Premium problem context

Unlock deeper context for this problem

Premium adds guided hints, editorial links, similar variants, discussion resources, and concept maps so you can understand why a problem matters, not just solve it once.

Guided hints
Editorial and discussion links
Concept map and variants
Sign in to unlock
Track your progress
Sign in to bookmark this problem, save notes, and manage its revision plan.