πΉ Problem: 1323. Maximum 69 Number
Difficulty: #Easy
Tags: #Greedy, #Math
π Problem Summary
Youβre given a positive integer made up of only digits
6
and9
. You are allowed to change at most one digit (6 β 9
or9 β 6
).
The goal is to maximize the resulting number.
π§ My Thought Process
Brute Force Idea:
Replace each6
with9
one by one, compute all possible numbers, and pick the maximum. This works, but itβs wasteful.-
Optimized Strategy (Greedy):
- To maximize, we only need to flip the leftmost
6
into9
. - Why? Because digits on the left have higher weight in decimal representation.
- No need to check further, just do a single replacement.
- To maximize, we only need to flip the leftmost
Algorithm Used:
Greedy + String Manipulation
βοΈ Code Implementation (Python)
class Solution:
def maximum69Number (self, num: int) -> int:
# Convert number to string for easy manipulation
num = str(num)
# Replace only the first '6' with '9'
num = num.replace('6', '9', 1)
# Convert back to int and return
return int(num)
β±οΈ Time & Space Complexity
- Time: O(n), where n = number of digits (string scan + replacement).
- Space: O(n) due to string conversion.
π§© Key Takeaways
- β Greedy worked because we only need to maximize once at the highest place value.
- π‘ Learned that string manipulation can often simplify digit-based problems.
- π Similar problems often involve changing the most significant digit first.
π Reflection (Self-Check)
- [x] Could I solve this without help?
- [x] Did I write code from scratch?
- [x] Did I understand why it works?
- [x] Will I be able to recall this in a week?
π Progress Tracker
Metric | Value |
---|---|
Day | 61 |
Total Problems Solved | 417 |
Confidence Today | π |
Leetcode Rating | 1572 |
Top comments (0)