[Løst] Max Sequence of Equal Elements - PHP Array Task

  

5
Emne starter

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:

max sequence of equal elements php array task

2 Svar
4

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

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);
Del: