#1432

Max Difference You Can Get From Changing an Integer

Medium
MathGreedyGreedyString Manipulation
LeetCode ↗

Approaches

Brute ForceOptimal
Complexity Comparison
Brute ForceOptimal Solution
Time
O(n²)
O(n)
Space
O(1)
O(n)
💡

Intuition

Time O(n)Space O(n)

The optimal solution focuses on identifying the best and worst possible transformations in a single pass. By strategically choosing the digits to replace, we can efficiently compute the maximum and minimum values without redundant calculations.

⚙️

Algorithm

4 steps
  1. 1Step 1: Convert the integer num to a string to easily manipulate its digits.
  2. 2Step 2: Identify the maximum digit in the number and replace it with '9' to maximize the number.
  3. 3Step 3: Identify the minimum digit in the number (that is not '0') and replace it with '1' to minimize the number.
  4. 4Step 4: Calculate the difference between the maximum and minimum values obtained from the transformations.
solution.py5 lines
1def maxDifference(num):
2    num_str = str(num)
3    max_num = num_str.replace(max(num_str), '9')
4    min_num = num_str.replace(min(num_str.replace('0', '')), '1')
5    return int(max_num) - int(min_num)

Complexity note: The time complexity is O(n) because we traverse the number a few times (finding max and min digits). The space complexity is O(n) due to the string manipulations.

  • 1Identifying the maximum and minimum digits is crucial for maximizing and minimizing the number.
  • 2Replacing digits strategically can lead to significant differences.

Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.