5
22/10/2024 4:48 pm
トピックスターター
Write a program that finds the longest sequence of equal elements in an array of integers. If several longest sequences exist, print the leftmost one.
Examples:

2件の回答
4
22/10/2024 4:49 pm
My answer:
<?php
$array = array_map('intval', explode(' ', readline()));
$count = count($array);
$bestCount = 0;
$bestElement = 0;
for ($i = 0; $i < $count; $i++) {
$repeat = 1;
for ($j = $i + 1; $j < $count; $j++) {
if ($array[$i] == $array[$j]) {
$repeat++;
} else {
break;
}
}
if ($repeat > $bestCount) {
$bestCount = $repeat;
$bestElement = $array[$i];
}
}
for ($i = 0; $i < $bestCount; $i++) {
echo $bestElement . ' ';
}
3
22/10/2024 4:50 pm
To show the result (the last - 23rd line) you can also use str_repeat function in PHP:
str_repeat ( string $input , int $multiplier ) : string
Returns input repeated multiplier times.
input
The string to be repeated.
multiplier
Number of time the input string should be repeated
My code:
<?php
$array = array_map('intval', explode(' ', readline()));
$count = count($array);
$bestCount = 0;
$bestElement = 0;
for ($i = 0; $i < $count; $i++) {
$repeat = 1;
for ($j = $i + 1; $j < $count; $j++) {
if ($array[$i] == $array[$j]) {
$repeat++;
} else {
break;
}
}
if ($repeat > $bestCount) {
$bestCount = $repeat;
$bestElement = $array[$i];
}
}
echo str_repeat("$bestElement ", $bestCount);
