Maximum 69 Number — LeetCode 1323 Python Solution

EasyGreedyMath
Problem
#1323
Pattern
Greedy
Reading time
2 min

The problem

You are given a positive integer num consisting only of digits 6 and 9. Return the maximum number you can get by changing at most one digit (6 becomes 9, and 9 becomes 6).

Example

Input
num = 9669
Output
9969
Explanation
Changing the first digit results in 6669.

Python solution

Python
class Solution:
    def maximum69Number(self, num: int) -> int:
        return int(str(num).replace("6", "9", 1))

Complexity

MeasureComplexity
TimeO(n log n)
SpaceO(1) to O(n) auxiliary

Pattern: Greedy

Take the locally best option every time — when you can prove that never costs you later. LeetCode 1323. Maximum 69 Number is filed here on both counts: the reference solution below belongs to the algorithm family this hub collects, and LeetCode tags it Greedy.

The greedy guide has the Python template for the pattern and the 346 LeetCode problems that use it.

Related problems

Frequently asked questions

How hard is LeetCode 1323. Maximum 69 Number?
LeetCode 1323. Maximum 69 Number is rated Easy on LeetCode.
What topics does LeetCode 1323. Maximum 69 Number cover?
LeetCode 1323. Maximum 69 Number is tagged Greedy and Math on LeetCode.

Stuck on problems like this in a live interview?

Stealth Interview is a desktop app for macOS and Windows. It reads the problem off your screen and returns a working solution with a step-by-step explanation and its time and space complexity — invisible to screen sharing.

Get Stealth Interview