We use cookies (including Google cookies) to personalize ads and analyze traffic. By continuing to use our site, you accept our Privacy Policy.

Max Difference You Can Get From Changing an Integer

Difficulty: Medium


Problem Description

You are given an integer num. You will apply the following steps exactly two times:

  1. Pick a digit x (0 <= x <= 9).
  2. Pick another digit y (0 <= y <= 9). The digit y can be equal to x.
  3. Replace all the occurrences of x in the decimal representation of num by y.
  4. The new integer cannot have any leading zeros, also the new integer cannot be 0.

Let a and b be the results of applying the operations to num the first and second times, respectively. Return the max difference between a and b.


Key Insights

  • You can change the digits in num to maximize the difference between the two resulting integers.
  • To maximize the larger number, replace the most significant digit with the largest possible digit (9) and any others with the same digit.
  • To minimize the smaller number, replace the most significant digit with the smallest possible non-zero digit (1 or another digit) and other digits with the smallest possible digit (0 or 1).
  • Special care must be taken to avoid leading zeros in the new integers.

Space and Time Complexity

Time Complexity: O(n), where n is the number of digits in the integer num. Space Complexity: O(1), since we are using a constant amount of space regardless of the input size.


Solution

To solve the problem, we need to:

  1. Convert the integer num into its string representation.
  2. For the first operation, find a digit x to replace with y in order to maximize the new integer. This involves replacing all occurrences of the most significant digit with 9.
  3. For the second operation, find a digit x to replace with y to minimize the new integer. This involves replacing the most significant digit while ensuring no leading zero occurs.
  4. Calculate the maximum difference between the two results.

The algorithm primarily uses string manipulation to achieve the desired transformations.


Code Solutions

def maxDifference(num: int) -> int:
    num_str = str(num)

    # Maximize the number
    max_num_str = num_str.replace(num_str[0], '9')
    max_num = int(max_num_str)

    # Minimize the number, ensuring no leading zeros
    min_num_str = num_str.replace(num_str[0], '1', 1)  # Replace only the first occurrence
    if min_num_str[0] == '0':  # if it leads to zero, revert back
        min_num_str = num_str.replace(num_str[0], '0', 1)
    min_num = int(min_num_str)

    return max_num - min_num
← Back to All Questions