Facebook Pixel

3536. Maximum Product of Two Digits

Problem Description

You are given a positive integer n. The task is to return the maximum product of any two digits in n. Note that you may use the same digit twice if it appears more than once in n.

Intuition

To solve this problem, we need to determine which two digits from the given integer n yield the highest product. The most straightforward approach is to identify the two largest digits in the number and calculate their product. This makes sense because the multiplication of the highest numbers results in the largest product. We will iterate through each digit of n, maintaining two variables: a and b. a holds the largest digit encountered thus far, and b holds the second largest. As we examine each digit, we compare it with a. If it surpasses a, we update b to take on the old value of a, and then set a to the new larger digit. If the digit does not exceed a but is greater than b, we simply assign it to b. Finally, the maximum product is a * b.

Solution Approach

In the solution, we are using a simple iterative approach to determine the two largest digits in the integer n. Here's how the implementation works:

  1. Initialize Two Variables: We start by initializing two variables, a and b, to zero. These will store the largest and second largest digits, respectively.

  2. Iterate Over Digits: We use a while loop to process every digit of n. In each iteration, we use the divmod function, which returns the quotient and remainder when n is divided by 10. Here, the quotient becomes the updated value of n, and the remainder, x, is the current rightmost digit.

  3. Updating Largest and Second Largest:

    • If the current digit x is greater than a, then b is updated to the value of a, and a is updated to x.
    • If x is not greater than a but is greater than b, then b is updated to x.
  4. Calculate and Return the Product: Once the loop completes, we have the two largest digits stored in a and b. We simply return their product a * b.

This approach efficiently finds the largest and second largest digits in O(d) time complexity, where d is the number of digits in n, and calculates the desired maximum product.

Ready to land your dream job?

Unlock your dream job with a 2-minute evaluator for a personalized learning plan!

Start Evaluator

Example Walkthrough

Let's walk through an example with n = 29458.

  1. Initialization: Start with a = 0 and b = 0.

  2. Iteration Begins:

    • Step 1:

      • Current n = 29458. Using divmod(29458, 10), we get quotient 2945 and remainder 8.
      • Compare 8 with a (0). Since 8 > 0, update b to a's value (0), and set a = 8.
    • Step 2:

      • Current n = 2945. Using divmod(2945, 10), we get quotient 294 and remainder 5.
      • Compare 5 with a (8) and b (0). 5 isn't greater than a, but greater than b, so update b = 5.
    • Step 3:

      • Current n = 294. Using divmod(294, 10), we get quotient 29 and remainder 4.
      • Compare 4 with a (8) and b (5). 4 isn't greater than a or b, hence no updates.
    • Step 4:

      • Current n = 29. Using divmod(29, 10), we get quotient 2 and remainder 9.
      • Compare 9 with a (8). Since 9 > 8, update b = 8, and set a = 9.
    • Step 5:

      • Current n = 2. Using divmod(2, 10), we get quotient 0 and remainder 2.
      • Compare 2 with a (9) and b (8). 2 isn't greater than a or b, hence no updates.
  3. Result: After processing all digits, largest a = 9 and second largest b = 8. The maximum product is 9 * 8 = 72.

Thus, the maximum product of any two digits in 29458 is 72.

Solution Implementation

1class Solution:
2    def maxProduct(self, n: int) -> int:
3        # Initialize the two largest digits to zero
4        largest_digit = second_largest_digit = 0
5      
6        # Loop through digits of n
7        while n > 0:
8            n, current_digit = divmod(n, 10)  # Extract the last digit
9          
10            # Update the largest and second-largest digits if necessary
11            if largest_digit < current_digit:
12                largest_digit, second_largest_digit = current_digit, largest_digit
13            elif second_largest_digit < current_digit:
14                second_largest_digit = current_digit
15      
16        # Return the product of the two largest digits
17        return largest_digit * second_largest_digit
18
1class Solution {
2    public int maxProduct(int number) {
3        int maxDigit1 = 0, maxDigit2 = 0;
4
5        // Iterate through the digits of the number
6        while (number > 0) {
7            int currentDigit = number % 10;
8
9            // Update the two largest digits found so far
10            if (maxDigit1 < currentDigit) {
11                maxDigit2 = maxDigit1;
12                maxDigit1 = currentDigit;
13            } else if (maxDigit2 < currentDigit) {
14                maxDigit2 = currentDigit;
15            }
16
17            // Move to the next digit
18            number /= 10;
19        }
20
21        // Return the product of the two largest digits
22        return maxDigit1 * maxDigit2;
23    }
24}
25
1class Solution {
2public:
3    int maxProduct(int n) {
4        int largest = 0; // Largest digit found
5        int secondLargest = 0; // Second largest digit found
6
7        // Loop through each digit in number n
8        for (; n > 0; n /= 10) {
9            int currentDigit = n % 10; // Get the last digit of n
10
11            // Check if the current digit is greater than the largest found so far
12            if (largest < currentDigit) {
13                secondLargest = largest; // Update the second largest
14                largest = currentDigit; // Update the largest
15            } 
16            // Check if the current digit is greater than the second largest
17            else if (secondLargest < currentDigit) {
18                secondLargest = currentDigit; // Update the second largest
19            }
20        }
21      
22        // Return the product of the two largest digits found
23        return largest * secondLargest;
24    }
25};
26
1// Function to find the maximum product of two digits in a given number 
2function maxProduct(n: number): number {
3    // Initialize variables to store the two largest digits
4    let largestDigit = 0;
5    let secondLargestDigit = 0;
6  
7    // Iterate over each digit in the number
8    while (n > 0) {
9        // Extract the last digit of the number
10        const currentDigit = n % 10;
11      
12        // Check if the current digit is greater than the largest digit found so far
13        if (largestDigit < currentDigit) {
14            // Update largest and second largest digits
15            [largestDigit, secondLargestDigit] = [currentDigit, largestDigit];
16        } else if (secondLargestDigit < currentDigit) {
17            // Update only the second largest digit if applicable
18            secondLargestDigit = currentDigit;
19        }
20      
21        // Remove the last digit from the number
22        n = Math.floor(n / 10);
23    }
24  
25    // Return the product of the two largest digits
26    return largestDigit * secondLargestDigit;
27}
28

Time and Space Complexity

The time complexity of the given code is O(\log n), where n is the input number. This is because in each iteration of the while loop, the number n is reduced by a factor of 10 (using divmod(n, 10)), and the loop continues until n becomes 0. Therefore, the number of iterations is proportional to the number of digits in n, which is O(\log n).

The space complexity of the code is O(1). This is because the algorithm uses a constant amount of space regardless of the size of the input. The space is used for storing the variables a, b, and x, and no additional data structures that grow with input size are used.


Discover Your Strengths and Weaknesses: Take Our 2-Minute Quiz to Tailor Your Study Plan:

What's the output of running the following function using input 56?

1KEYBOARD = {
2    '2': 'abc',
3    '3': 'def',
4    '4': 'ghi',
5    '5': 'jkl',
6    '6': 'mno',
7    '7': 'pqrs',
8    '8': 'tuv',
9    '9': 'wxyz',
10}
11
12def letter_combinations_of_phone_number(digits):
13    def dfs(path, res):
14        if len(path) == len(digits):
15            res.append(''.join(path))
16            return
17
18        next_number = digits[len(path)]
19        for letter in KEYBOARD[next_number]:
20            path.append(letter)
21            dfs(path, res)
22            path.pop()
23
24    res = []
25    dfs([], res)
26    return res
27
1private static final Map<Character, char[]> KEYBOARD = Map.of(
2    '2', "abc".toCharArray(),
3    '3', "def".toCharArray(),
4    '4', "ghi".toCharArray(),
5    '5', "jkl".toCharArray(),
6    '6', "mno".toCharArray(),
7    '7', "pqrs".toCharArray(),
8    '8', "tuv".toCharArray(),
9    '9', "wxyz".toCharArray()
10);
11
12public static List<String> letterCombinationsOfPhoneNumber(String digits) {
13    List<String> res = new ArrayList<>();
14    dfs(new StringBuilder(), res, digits.toCharArray());
15    return res;
16}
17
18private static void dfs(StringBuilder path, List<String> res, char[] digits) {
19    if (path.length() == digits.length) {
20        res.add(path.toString());
21        return;
22    }
23    char next_digit = digits[path.length()];
24    for (char letter : KEYBOARD.get(next_digit)) {
25        path.append(letter);
26        dfs(path, res, digits);
27        path.deleteCharAt(path.length() - 1);
28    }
29}
30
1const KEYBOARD = {
2    '2': 'abc',
3    '3': 'def',
4    '4': 'ghi',
5    '5': 'jkl',
6    '6': 'mno',
7    '7': 'pqrs',
8    '8': 'tuv',
9    '9': 'wxyz',
10}
11
12function letter_combinations_of_phone_number(digits) {
13    let res = [];
14    dfs(digits, [], res);
15    return res;
16}
17
18function dfs(digits, path, res) {
19    if (path.length === digits.length) {
20        res.push(path.join(''));
21        return;
22    }
23    let next_number = digits.charAt(path.length);
24    for (let letter of KEYBOARD[next_number]) {
25        path.push(letter);
26        dfs(digits, path, res);
27        path.pop();
28    }
29}
30

Recommended Readings

Want a Structured Path to Master System Design Too? Don’t Miss This!

Load More