fork(1) download
  1. <?php
  2.  
  3. function getTwoMaxOfArray(array $array) {
  4. $arrCount = count($array);
  5. if ($arrCount < 3) {
  6. return $array;
  7. }
  8.  
  9. $firstMax = $array[0];
  10. $secondMax = $array[0];
  11. for ($i = 1; $i < $arrCount; $i++) {
  12. if ($array[$i] === $firstMax || $array[$i] === $secondMax) {
  13. continue;
  14. }
  15. if ($array[$i] > $firstMax) {
  16. $secondMax = $firstMax;
  17. $firstMax = $array[$i];
  18. } elseif ($array[$i] > $secondMax || $secondMax === $firstMax) {
  19. $secondMax = $array[$i];
  20. }
  21. }
  22.  
  23. return [$firstMax, $secondMax];
  24. }
  25.  
  26. assert([] === getTwoMaxOfArray([]));
  27. assert([1] === getTwoMaxOfArray([1]));
  28. assert([2, 1] === getTwoMaxOfArray([2, 1]));
  29. assert([4, 3] === getTwoMaxOfArray([2, 3, 4]));
  30. assert([3, 2] === getTwoMaxOfArray([1, 2, 2, 2, 3, 3]));
  31. assert([3, 1] === getTwoMaxOfArray([1, 1, 1, 3, 3]));
  32. assert([3, 2] === getTwoMaxOfArray([3, 3, 3, 2, 2, 1, 1, 1]));
  33. assert([3, 2] === getTwoMaxOfArray([3, 3, 3, 2]));
  34. assert([3, 2] === getTwoMaxOfArray([3, 2, 1]));
  35. assert([3, 2] === getTwoMaxOfArray([1, 2, 3]));
  36.  
  37.  
Success #stdin #stdout 0.01s 52488KB
stdin
Standard input is empty
stdout
Standard output is empty