Skip to main content
Back to problems
Leetcode
Medium
Math
Greedy
Strings
Amazon
Max Difference You Can Get From Changing an Integer

Change digits of an integer twice to maximize the difference between the largest and smallest possible values.

Acceptance 100%
Problem Statement

Problem

You are given a non-negative integer num. You may perform the following operation twice, independently:

  • Pick one digit in num and replace every occurrence of that digit with another digit from 0 to 9.

After one replacement, the resulting number must still be a valid integer representation; in particular, it cannot have leading zeros unless the number itself is 0.

Your goal is to maximize the difference between the value obtained by making a best possible replacement to create a large number and the value obtained by making a best possible replacement to create a small number.

Return that maximum difference.

Notes

  • You may choose different digits for the maximizing and minimizing transformations.
  • Replacements apply to all occurrences of the chosen digit.
  • The original number is given in decimal form.

Input Format

  • A single integer num.

You may treat it as a decimal string of digits for the purpose of replacement.

Output Format

  • Return one integer: the maximum possible difference between the best larger transformed value and the best smaller transformed value.

Constraints

  • 0 <= num <= $10^{8}$
  • num contains no leading zeros unless it is exactly 0.
  • Any replacement must keep the number a valid decimal integer representation.
Examples
Sample cases returned by the problem API.

Example 1

Input

num = 555

Output

888

Explanation

To maximize, change all 5 to 9 to get 999. To minimize, changing 5 to 1 gives 111. The difference is 999 - 111 = 888.

Example 2

Input

num = 9

Output

8

Explanation

The best maximum value is 9 itself. The smallest valid value is 1, obtained by changing 9 to 1. The difference is 8.

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.