A good way into this one is to ask: what do we need to remember so we never redo work blindly? For 1323. Maximum 69 Number, the solution in this repository is mainly a straightforward implementation solution.
Guide
What?
The first job is to translate the English prompt into state, transition, and stopping conditions. Instead of trying to be clever immediately, read the code as a sequence of questions:
- What state are we keeping?
- How do we move from one state to the next?
- When do we know the answer is already determined?
For this file, the main tools are: straightforward implementation.
Guide
When?
This is the kind of solution you want when the problem has structure hiding inside a messy-looking input. The accepted code reduces that pressure by storing exactly the information that remains useful later.
The important function names to track are maximum69Number.
Guide
Why?
The win comes from making each line carry responsibility: store the useful state, discard the rest, keep moving.
- The final return is not magic; it is the invariant after the loops or recursion have finished doing their accounting.
Guide
How?
Walk through the solution in this order:
- Read the setup variables first.
- Follow the main loop or recursive helper next.
- Watch where invalid states get skipped.
- Check which value survives to the return statement.
The most important competitive-programming habit here is to trust the invariant. Once the invariant is right, the loops become much less scary.
Guide
Complexity
- Time: O(n) to O(n log n), depending on the dominant loop or data structure operation
- Space: O(n) in the usual case for auxiliary containers or recursion
Guide
C++ Solution
Your submission
The accepted solution
01//Runtime: 0 ms, faster than 100.00% of C++ online submissions for Maximum 69 Number.
02//Memory Usage: 7.6 MB, less than 100.00% of C++ online submissions for Maximum 69 Number.
03
04class Solution {
05public:
06 int maximum69Number (int num) {
07 vector<int> arr;
08 while(num){
09 arr.insert(arr.begin(), num%10);
10 num /= 10;
11 }
12
13 bool converted = false;
14 int ans = 0;
15 for(int i = 0; i < arr.size(); i++){
16 if(arr[i] != 9 && !converted){
17 arr[i] = 9;
18 converted = true;
19 }
20 ans = ans * 10 + arr[i];
21 }
22
23 return ans;
24 }
25};
Cost