3208. Alternating Groups II #1409
-
Topics: There is a circle of red and blue tiles. You are given an array of integers
An alternating group is every Return the number of alternating groups. Note that since Example 1:
Example 2:
Example 3:
Constraints:
Hint:
|
Beta Was this translation helpful? Give feedback.
Replies: 1 comment 2 replies
-
We need to count the number of alternating groups of size Approach
Let's implement this solution in PHP: 3208. Alternating Groups II <?php
/**
* @param Integer[] $colors
* @param Integer $k
* @return Integer
*/
function numberOfAlternatingGroups($colors, $k) {
$n = count($colors);
if ($k > $n) {
return 0;
}
$s = $k - 1;
// Compute valid array
$valid = array();
for ($i = 0; $i < $n; $i++) {
$j = ($i + 1) % $n;
$valid[] = ($colors[$i] != $colors[$j]) ? 1 : 0;
}
// Check if all valid are 1
$totalValid = array_sum($valid);
if ($totalValid == $n) {
return $n;
}
// Split into runs
$runs = array();
$current = $valid[0];
$count = 1;
for ($i = 1; $i < $n; $i++) {
if ($valid[$i] == $current) {
$count++;
} else {
$runs[] = array('val' => $current, 'len' => $count);
$current = $valid[$i];
$count = 1;
}
}
$runs[] = array('val' => $current, 'len' => $count);
// Merge first and last runs if both are 1
if (!empty($runs)) {
$first = $runs[0];
$last = end($runs);
if ($first['val'] == 1 && $last['val'] == 1) {
$mergedLen = $first['len'] + $last['len'];
$newRuns = array();
$newRuns[] = array('val' => 1, 'len' => $mergedLen);
$numRuns = count($runs);
if ($numRuns > 2) {
for ($i = 1; $i < $numRuns - 1; $i++) {
$newRuns[] = $runs[$i];
}
}
$runs = $newRuns;
}
}
// Calculate total valid windows
$total = 0;
foreach ($runs as $run) {
if ($run['val'] == 1) {
$L = $run['len'];
if ($L >= $s) {
$total += $L - $s + 1;
}
}
}
return $total;
}
// Test cases
echo numberOfAlternatingGroups([0,1,0,1,0], 3) . "\n"; // Output: 3
echo numberOfAlternatingGroups([0,1,0,0,1,0,1], 6) . "\n"; // Output: 2
echo numberOfAlternatingGroups([1,1,0,1], 4) . "\n"; // Output: 0
?> Explanation:
|
Beta Was this translation helpful? Give feedback.
We need to count the number of alternating groups of size
k
in a circular array of colors. An alternating group is defined as a sequence ofk
contiguous tiles where each tile (except the first and last) has a different color from both its left and right neighbors.Approach
valid
array where each element is1
if the corresponding consecutive elements in the originalcolors
array are different, and0
otherwise. This helps us identify positions where consecutive elements do not form an alternating pattern.valid
array are1
, it means the entire array is already alternating, and every possible window of s…