3536. Maximum Product of Two Digits LeetCode Solution
In this guide, you will get 3536. Maximum Product of Two Digits LeetCode Solution with the best time and space complexity. The solution to Maximum Product of Two Digits problem is provided in various programming languages like C++, Java, and Python. This will be helpful for you if you are preparing for placements, hackathons, interviews, or practice purposes. The solutions provided here are very easy to follow and include detailed explanations.
Table of Contents
- Problem Statement
- Complexity Analysis
- Maximum Product of Two Digits solution in C++
- Maximum Product of Two Digits solution in Java
- Maximum Product of Two Digits solution in Python
- Additional Resources
Problem Statement of Maximum Product of Two Digits
You are given a positive integer n.
Return the maximum product of any two digits in n.
Note: You may use the same digit twice if it appears more than once in n.
Example 1:
Input: n = 31
Output: 3
Explanation:
The digits of n are [3, 1].
The possible products of any two digits are: 3 * 1 = 3.
The maximum product is 3.
Example 2:
Input: n = 22
Output: 4
Explanation:
The digits of n are [2, 2].
The possible products of any two digits are: 2 * 2 = 4.
The maximum product is 4.
Example 3:
Input: n = 124
Output: 8
Explanation:
The digits of n are [1, 2, 4].
The possible products of any two digits are: 1 * 2 = 2, 1 * 4 = 4, 2 * 4 = 8.
The maximum product is 8.
Constraints:
10 <= n <= 109
Complexity Analysis
- Time Complexity: O(n)
- Space Complexity: O(n)
3536. Maximum Product of Two Digits LeetCode Solution in C++
class Solution {
public:
int maxProduct(int n) {
string s = to_string(n);
ranges::sort(s);
const int sz = s.length();
return (s[sz - 1] - '0') * (s[sz - 2] - '0');
}
};
/* code provided by PROGIEZ */
3536. Maximum Product of Two Digits LeetCode Solution in Java
class Solution {
public int maxProduct(int n) {
char[] s = String.valueOf(n).toCharArray();
Arrays.sort(s);
final int sz = s.length;
return (s[sz - 1] - '0') * (s[sz - 2] - '0');
}
}
// code provided by PROGIEZ
3536. Maximum Product of Two Digits LeetCode Solution in Python
class Solution:
def maxProduct(self, n: int) -> int:
s = sorted(str(n))
return int(s[-1]) * int(s[-2])
# code by PROGIEZ
Additional Resources
- Explore all LeetCode problem solutions at Progiez here
- Explore all problems on LeetCode website here
Happy Coding! Keep following PROGIEZ for more updates and solutions.