Last active
August 23, 2019 21:56
-
-
Save eryshkov/17ed8514bc5215da7d171c02b6a3077a to your computer and use it in GitHub Desktop.
[handleArray function] РЭЛЭКС интервью
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
/** | |
* Задание: найти в заданном массиве наибольшую по количеству элементов последовательность, в которой все элементы возрастают. | |
*/ | |
function handleArray(array $array) | |
{ | |
$lastKey = array_key_last($array); | |
$bestLength = 0; | |
$bestPosition = 0; | |
$currentLength = 0; | |
$startPosition = 0; | |
foreach ($array as $currentKey => $currentValue) { | |
if (!isset($prevValue)) { | |
$prevValue = $currentValue; | |
$currentLength++; | |
continue; | |
} | |
if (($currentKey === $lastKey) && ($currentValue > $prevValue)) { | |
$currentLength++; | |
if ($currentLength >= $bestLength) { | |
return ['bestLength' => $currentLength, 'bestPosition' => $startPosition]; | |
} | |
} | |
if ($currentValue > $prevValue) { | |
$prevValue = $currentValue; | |
$currentLength++; | |
continue; | |
} else { | |
if ($currentLength >= $bestLength) { | |
$bestLength = $currentLength; | |
$bestPosition = $startPosition; | |
} | |
$startPosition = $currentKey; | |
$prevValue = $currentValue; | |
$currentLength = 1; | |
continue; | |
} | |
} | |
return ['bestLength' => $bestLength, 'bestPosition' => $bestPosition]; | |
} | |
$array = [1, 2, 3, 4, -1, 0, 1, 2, 3, 4, 1, 2, 3, 4, 5, 6, 1, 2]; | |
//$array = [1, 2, 0, 1, 2]; | |
$result = handleArray($array); | |
var_dump($result); |
- второй массив лишний
если массив просматривается только один раз слева направо, то он не нужен- сортировка вместо поиска максимального элемента - это дорогое неоптимальное решение
Внес исправления:
- Удалил ненужный массив
- Сделал поиск максимального элемента в том же цикле, который перебирает массив.
Решение не идеальное, но гораздо лучше предыдущего
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
если массив просматривается только один раз слева направо, то он не нужен