1726. Tuple with Same Product #1279
-
Topics: Given an array Example 1:
Example 2:
Constraints:
Hint:
|
Beta Was this translation helpful? Give feedback.
Replies: 1 comment 2 replies
-
We need to determine the number of valid tuples (a, b, c, d) from a given array of distinct positive integers such that the product of a and b is equal to the product of c and d, with all four elements being distinct. Approach
Let's implement this solution in PHP: 1726. Tuple with Same Product <?php
/**
* @param Integer[] $nums
* @return Integer
*/
function tupleSameProduct($nums) {
$productCounts = array();
$n = count($nums);
for ($i = 0; $i < $n; $i++) {
for ($j = $i + 1; $j < $n; $j++) {
$prod = $nums[$i] * $nums[$j];
if (isset($productCounts[$prod])) {
$productCounts[$prod]++;
} else {
$productCounts[$prod] = 1;
}
}
}
$total = 0;
foreach ($productCounts as $count) {
if ($count >= 2) {
$total += 4 * $count * ($count - 1);
}
}
return $total;
}
// Example 1
$nums1 = [2, 3, 4, 6];
echo "Output: " . tupleSameProduct($nums1) . "\n"; // Output: 8
// Example 2
$nums2 = [1, 2, 4, 5, 10];
echo "Output: " . tupleSameProduct($nums2) . "\n"; // Output: 16
?> Explanation:
This approach efficiently counts all valid tuples by leveraging combinatorial counting and hash maps to track product frequencies, ensuring an optimal solution within the problem |
Beta Was this translation helpful? Give feedback.
We need to determine the number of valid tuples (a, b, c, d) from a given array of distinct positive integers such that the product of a and b is equal to the product of c and d, with all four elements being distinct.
Approach