Skip to content

Instantly share code, notes, and snippets.

@eryshkov
Last active August 23, 2019 21:56
Show Gist options
  • Save eryshkov/17ed8514bc5215da7d171c02b6a3077a to your computer and use it in GitHub Desktop.
Save eryshkov/17ed8514bc5215da7d171c02b6a3077a to your computer and use it in GitHub Desktop.
[handleArray function] РЭЛЭКС интервью
<?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);
@vmmelnikov
Copy link

  1. второй массив лишний
    если массив просматривается только один раз слева направо, то он не нужен
  2. сортировка вместо поиска максимального элемента - это дорогое неоптимальное решение

@eryshkov
Copy link
Author

eryshkov commented Aug 23, 2019

  • второй массив лишний
    если массив просматривается только один раз слева направо, то он не нужен
  • сортировка вместо поиска максимального элемента - это дорогое неоптимальное решение

Внес исправления:

  1. Удалил ненужный массив
  2. Сделал поиск максимального элемента в том же цикле, который перебирает массив.

Решение не идеальное, но гораздо лучше предыдущего

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment