CountDiv
Should use merge sort for best performance, but because I didn't know how to do it yet, so I'll leave it like this for now.
function solution($A) { //// Brute-force way // $n = count($A); // $max = null; // for($p = 0; $p < $n - 2; $p++) { // for($q = $p + 1; $q < $n -1; $q++) { // for($r = $q + 1; $r < $n; $r++) { // $product = $A[$p] * $A[$q] * $A[$r]; // if($max === null || $max < $product){ // $max = $product; // } // } // } // } // Better way $p = null; $q = null; $r = null; $p1 = null; $q1 = null; $r1 = null; foreach($A as $val){ if($p === null || $val >= $p) { $r = $q; $q = $p; $p = $val; }elseif($q === null || $val >= $q) { $r = $q; $q = $val; }elseif($r === null || $val >= $r) { $r = $val; } if($p1 === null || $val <= $p1) { $r1 = $q1; $q1 = $p1; $p1 = $val; }elseif($q1 === null || $val <= $q1) { $r1 = $q1; $q1 = $val; }elseif($r1 === null || $val <= $r1) { $r1 = $val; } } if($p >= 0){ if($r <= 0 || $p1 * $q1 > $q * $r) { $q = $p1; $r = $q1; } } return $p*$q*$r; }