#1323

Maximum 69 Number

Easy
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 leverages the fact that we only need to change the first occurrence of '6' to '9' to maximize the number. This is because changing a '6' to '9' at a higher place value increases the overall number more than changing a '9' to '6'.

⚙️

Algorithm

3 steps
  1. 1Step 1: Convert the number to a string.
  2. 2Step 2: Find the first occurrence of '6'.
  3. 3Step 3: Change that '6' to '9' and return the new number.
solution.py7 lines
1def maximum69Number (num):
2    num_str = list(str(num))
3    for i in range(len(num_str)):
4        if num_str[i] == '6':
5            num_str[i] = '9'
6            break
7    return int(''.join(num_str))

Complexity note: The time complexity is O(n) because we only traverse the string once to find the first '6'. The space complexity is O(n) due to the string conversion.

  • 1Changing the first '6' to '9' maximizes the number.
  • 2Only one change is needed to achieve the maximum.

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