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:
-
Initialize Two Variables: We start by initializing two variables,
a
andb
, to zero. These will store the largest and second largest digits, respectively. -
Iterate Over Digits: We use a
while
loop to process every digit ofn
. In each iteration, we use thedivmod
function, which returns the quotient and remainder whenn
is divided by 10. Here, the quotient becomes the updated value ofn
, and the remainder,x
, is the current rightmost digit. -
Updating Largest and Second Largest:
- If the current digit
x
is greater thana
, thenb
is updated to the value ofa
, anda
is updated tox
. - If
x
is not greater thana
but is greater thanb
, thenb
is updated tox
.
- If the current digit
-
Calculate and Return the Product: Once the loop completes, we have the two largest digits stored in
a
andb
. We simply return their producta * 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 EvaluatorExample Walkthrough
Let's walk through an example with n = 29458
.
-
Initialization: Start with
a = 0
andb = 0
. -
Iteration Begins:
-
Step 1:
- Current
n = 29458
. Usingdivmod(29458, 10)
, we get quotient2945
and remainder8
. - Compare
8
witha
(0
). Since8
>0
, updateb
toa
's value (0
), and seta = 8
.
- Current
-
Step 2:
- Current
n = 2945
. Usingdivmod(2945, 10)
, we get quotient294
and remainder5
. - Compare
5
witha
(8
) andb
(0
).5
isn't greater thana
, but greater thanb
, so updateb = 5
.
- Current
-
Step 3:
- Current
n = 294
. Usingdivmod(294, 10)
, we get quotient29
and remainder4
. - Compare
4
witha
(8
) andb
(5
).4
isn't greater thana
orb
, hence no updates.
- Current
-
Step 4:
- Current
n = 29
. Usingdivmod(29, 10)
, we get quotient2
and remainder9
. - Compare
9
witha
(8
). Since9
>8
, updateb = 8
, and seta = 9
.
- Current
-
Step 5:
- Current
n = 2
. Usingdivmod(2, 10)
, we get quotient0
and remainder2
. - Compare
2
witha
(9
) andb
(8
).2
isn't greater thana
orb
, hence no updates.
- Current
-
-
Result: After processing all digits, largest
a = 9
and second largestb = 8
. The maximum product is9 * 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.
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
Coding Interview Patterns Your Personal Dijkstra's Algorithm to Landing Your Dream Job The goal of AlgoMonster is to help you get a job in the shortest amount of time possible in a data driven way We compiled datasets of tech interview problems and broke them down by patterns This way
Recursion Recursion is one of the most important concepts in computer science Simply speaking recursion is the process of a function calling itself Using a real life analogy imagine a scenario where you invite your friends to lunch https assets algo monster recursion jpg You first call Ben and ask
Runtime Overview When learning about algorithms and data structures you'll frequently encounter the term time complexity This concept is fundamental in computer science and offers insights into how long an algorithm takes to complete given a certain input size What is Time Complexity Time complexity represents the amount of time
Want a Structured Path to Master System Design Too? Don’t Miss This!