Skip to content

Instantly share code, notes, and snippets.

@fintara
Last active January 1, 2016 23:49
Show Gist options
  • Save fintara/8218701 to your computer and use it in GitHub Desktop.
Save fintara/8218701 to your computer and use it in GitHub Desktop.
<?php
/**
* Напишете програма, която намира максимална редица от последователни еднакви елементи в масив.
* Пример: {2, 1, 1, 2, 3, 3, 2, 2, 2, 1} -> {2, 2, 2}.
*/
$array = [2,1,1,2,3,3,2,2,2,1];
//$array = [3,1,1,1,1,1,5,1,1,1,1,2,3,3,3];
$bestStart = 0;
$bestLength = 0;
$currentLength = 1;
for($i = 1; $i < count($array); $i++) {
if($array[$i] === $array[$i - 1]) {
$currentLength++;
} else {
if($currentLength >= $bestLength) {
$bestLength = $currentLength;
$bestStart = $i - $bestLength;
}
$currentLength = 1;
}
}
echo "Best start at {$bestStart}\n";
echo "Best length {$bestLength}\n";
for($i = $bestStart; $i < $bestStart + $bestLength; $i++) {
echo "{$array[$i]} ";
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment