How to find a pair with maximum product from int array in PHP

2 Answers

0 votes
function max_product_from_int_array($arr, &$item1, &$item2) { 
    $item1 = $arr[0];
    $item2 = $arr[1];
    $len = sizeof($arr);
   
    for ($i = 0; $i < $len; $i++) {
      for ($j = $i + 1; $j < $len; $j++) {
         if ($arr[$i] * $arr[$j] > $item1 * $item2) {
            $item1 = $arr[$i];
            $item2 = $arr[$j]; 
         }
      }
    }
} 

$arr = array(3, 9, 1, 3, 7, 0, 8, 4); 
$item1 = 0;
$item2 = 0;
     
max_product_from_int_array($arr, $item1, $item2);
     
echo $item1 . " " . $item2;
 
 
 
 
/*
run:
      
9 8
     
*/

 



answered Apr 16, 2019 by avibootz
0 votes
function maxProductPair(array $arr): array {
    if (count($arr) < 2) {
        throw new InvalidArgumentException("Array must contain at least two elements.");
    }

    $max1 = PHP_INT_MIN;
    $max2 = PHP_INT_MIN;
    $min1 = PHP_INT_MAX;
    $min2 = PHP_INT_MAX;

    foreach ($arr as $x) {

        // Track two largest values
        if ($x > $max1) {
            $max2 = $max1;
            $max1 = $x;
        } elseif ($x > $max2) {
            $max2 = $x;
        }

        // Track two smallest values
        if ($x < $min1) {
            $min2 = $min1;
            $min1 = $x;
        } elseif ($x < $min2) {
            $min2 = $x;
        }
    }

    $prodMax = $max1 * $max2;
    $prodMin = $min1 * $min2;

    return ($prodMax >= $prodMin)
        ? [$max1, $max2]
        : [$min1, $min2];
}


$arr = [3, 9, 1, 3, 8, 0, 4];

list($a, $b) = maxProductPair($arr);

echo "Max product pair: $a, $b\n";



/*
run:

Max product pair: 9, 8

*/

 



answered Dec 26, 2025 by avibootz
...