Maximum 69 Number — Solution in Python, Java & C++
Maximum 69 Number solution explained: step-by-step approach, complexity and code in Python, Java, C++ and JavaScript. An easy problem on math and greedy.
Maximum 69 Number is an easy coding problem on math and greedy, asked in Amazon and Adobe interviews.
- Difficulty: Easy
- Topics: Math, Greedy
- Asked at: Amazon, Adobe
- Time limit: 2 s
- Memory limit: 256 MB
- Languages: JavaScript, TypeScript, Python, Java, C++, C, C#, Go, Kotlin, Swift, Rust, PHP and Ruby
Problem statement
You are given a positive integer num consisting only of the digits 6 and 9.
Return the maximum number you can get by changing at most one digit — a 6 may become a 9, or a 9 may become a 6.
Example 1
Input: num = 9669
Output: 9969
Explanation: Changing the first 6 gives the largest result.
Example 2
Input: num = 9996
Output: 9999
Example 3
Input: num = 9999
Output: 9999
Explanation: No change is better than leaving it alone.
Constraints
1 <= num <= 10^4num consists only of the digits 6 and 9.
Hints for Maximum 69 Number
Hint 1
Turning a 9 into a 6 only ever makes the number smaller, so the single change must be 6 → 9.
Hint 2
Changing the leftmost 6 gains the most, because it sits in the highest place value.
Hint 3
If there is no 6 at all, return the number unchanged.
How to solve Maximum 69 Number
Only a 6 → 9 change can increase the value, and the leftmost 6 sits in the highest place, so flip exactly that digit.
Approach
- Find the index of the first
6in the decimal string. - If there is none, return
numunchanged. - Replace that character with
9and parse back.
Why it works
Changing a digit at position p alters the value by ±3·10^p; the gain is largest at the most significant position, and only a 6 can gain at all. Any other single change is dominated.
Complexity
- Time —
O(digits) - Space —
O(digits)
Pitfalls
- Replacing every 6 uses more than one change.
- An all-9 input has no 6 and must be returned as is.
Reference solution
Python
def maximum69Number(num: int) -> int:
s = str(num)
i = s.find("6")
if i < 0:
return num
return int(s[:i] + "9" + s[i + 1:])Java
public static int maximum69Number(int num) {
String s = String.valueOf(num);
int i = s.indexOf('6');
if (i < 0) return num;
return Integer.parseInt(s.substring(0, i) + "9" + s.substring(i + 1));
}C++
int maximum69Number(int num) {
string s = to_string(num);
size_t i = s.find('6');
if (i == string::npos) return num;
s[i] = '9';
return stoi(s);
}JavaScript
var maximum69Number = function(num) {
const s = String(num);
const i = s.indexOf("6");
if (i < 0) return num;
return parseInt(s.slice(0, i) + "9" + s.slice(i + 1), 10);
};Also on the editorial tab: C, C#, Go, Kotlin, PHP, Ruby, Rust, Swift, TypeScript.
All 337 math problems · the whole catalogue
Learn the technique: Greedy Algorithms