3536. Maximum Product of Two Digits #3393
Answered
by
mah-shamim
mah-shamim
asked this question in
Q&A
|
Topics: You are given a positive integer Return the maximum product of any two digits in Note: You may use the same digit twice if it appears more than once in Example 1:
Example 2:
Example 3:
Example 4:
Example 5:
Example 6:
Example 7:
Example 8:
Constraints:
Hint:
|
Answered by
mah-shamim
Jul 25, 2026
Replies: 1 comment 2 replies
|
We convert the integer to a string, split it into an array of digits, and then use a nested loop to compute the product of every pair of digits (ensuring we don't pair a digit with itself unless it appears twice). We track and return the maximum product found. Approach
Let's implement this solution in PHP: 3536. Maximum Product of Two Digits <?php
/**
* @param Integer $n
* @return Integer
*/
function maxProduct(int $n): int
{
$digits = array_map('intval', str_split((string)$n));
$maxProduct = 0;
for ($i = 0; $i < count($digits); $i++) {
for ($j = $i + 1; $j < count($digits); $j++) {
$product = $digits[$i] * $digits[$j];
if ($product > $maxProduct) {
$maxProduct = $product;
}
}
}
return $maxProduct;
}
// Test cases
echo maxProduct(31) . "\n"; // Output: 3
echo maxProduct(22) . "\n"; // Output: 4
echo maxProduct(124) . "\n"; // Output: 8
echo maxProduct(99) . "\n"; // Output: 81
echo maxProduct(101) . "\n"; // Output: 1
echo maxProduct(1000000000) . "\n"; // Output: 0
echo maxProduct(987) . "\n"; // Output: 72
echo maxProduct(555) . "\n"; // Output: 25
?>Explanation:
Complexity Analysis
|
2 replies
Answer selected by
basharul-siddike
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
We convert the integer to a string, split it into an array of digits, and then use a nested loop to compute the product of every pair of digits (ensuring we don't pair a digit with itself unless it appears twice). We track and return the maximum product found.
Approach
nto a string and then to an array of digits.maxProductto 0.ifrom 0 tolen(digits)-1.jfromi+1tolen(digits)-1(to avoid duplicate pairs).product = digits[i] * digits[j].maxProductifproductis larger.maxProductafter loops.Let's implement this solution in PHP: 3536. Maximum Product of Two Digits