settingsAccountsettings
By using our mini forum, you acknowledge that you have read and understand our Cookie Policy and Privacy Policy
Menusettings

Q: Max Sequence of Equal Elements - PHP Array Task

+4 votes

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

asked in PHP category by user Jolie Ann

2 Answers

+3 votes

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 . ' ';
}
answered by user matthew44
+2 votes

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);
answered by user mitko
...