




Sponsored
Sponsored
This approach uses a simple greedy algorithm to find the first occurrence of the digit '6' and replaces it with '9'. This ensures that the number is maximized by making a change that increases the most significant portion of the number.
Time Complexity: O(n), where n is the number of digits in num.
Space Complexity: O(n) for storing the string representation of num.
1using System;
2
3public class Solution {
4    public int Maximum69Number (int num) {
5        char[] numCharArray = num.ToString().ToCharArray();
6        for (int i = 0; i < numCharArray.Length; i++) {
7            if (numCharArray[i] == '6') {
8                numCharArray[i] = '9';
9                break;
10            }
11        }
12        return int.Parse(new string(numCharArray));
13    }
14
15    public static void Main(string[] args) {
16        Solution sol = new Solution();
17        Console.WriteLine(sol.Maximum69Number(9669));
18    }
19}The C# solution processes the number by converting it into a character array. It iterates over the array to switch the first '6' to '9', converts the changed array back to a number, and returns it.
This approach works directly with the number without converting it to a string. We find the first '6' from the leftmost side by using basic mathematical operations (division and modulo). We can calculate the position and change the digit using arithmetic transformations to make this efficient.
Time Complexity: O(1), as we have at most 4 digits to check.
Space Complexity: O(1), using constant space for computations.
1
public class Solution {
    public int Maximum69Number(int num) {
        int mod = 10000;
        for (int i = 4; i >= 0; i--) {
            if ((num / mod) % 10 == 6) {
                num += 3 * mod;
                break;
            }
            mod /= 10;
        }
        return num;
    }
    public static void Main(string[] args) {
        Solution sol = new Solution();
        Console.WriteLine(sol.Maximum69Number(9669));
    }
}The C# method counts on mathematical manipulation for each numeric position, altering digits directly without transitions to character types.