3405. Count the Number of Arrays with K Matching Adjacent Elements #1818
-
|
Topics: You are given three integers
Return the number of good arrays that can be formed. Since the answer may be very large, return it modulo 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 "good arrays" of size Approach
Let's implement this solution in PHP: 3405. Count the Number of Arrays with K Matching Adjacent Elements <?php
/**
* @param Integer $n
* @param Integer $m
* @param Integer $k
* @return Integer
*/
function countGoodArrays($n, $m, $k) {
$MOD = 1000000007;
$total_adjacent = $n - 1;
if ($k > $total_adjacent) {
return 0;
}
$fact = array();
$fact[0] = 1;
for ($i = 1; $i <= $total_adjacent; $i++) {
$fact[$i] = ($fact[$i-1] * $i) % $MOD;
}
$denom = ($fact[$k] * $fact[$total_adjacent - $k]) % $MOD;
$inv_denom = mod_pow($denom, $MOD-2, $MOD);
$binom = ($fact[$total_adjacent] * $inv_denom) % $MOD;
$exponent = $total_adjacent - $k;
$base_val = $m - 1;
$power = mod_pow($base_val, $exponent, $MOD);
$result = (($m % $MOD) * $binom) % $MOD;
$result = ($result * $power) % $MOD;
return $result;
}
/**
* Modular exponentiation
*
* @param $base
* @param $exponent
* @param $mod
* @return int
*/
function mod_pow($base, $exponent, $mod) {
if ($mod == 1) {
return 0;
}
$result = 1;
$base = $base % $mod;
while ($exponent > 0) {
if ($exponent & 1) {
$result = ($result * $base) % $mod;
}
$base = ($base * $base) % $mod;
$exponent = $exponent >> 1;
}
return $result;
}
// Example usage:
echo countGoodArrays(3, 2, 1) . "\n"; // Output: 4
echo countGoodArrays(4, 2, 2) . "\n"; // Output: 6
echo countGoodArrays(5, 2, 0) . "\n"; // Output: 2
?>Explanation:
This approach efficiently combines combinatorial mathematics with modular arithmetic to solve the problem within feasible computational limits, even for large inputs. |
Beta Was this translation helpful? Give feedback.
We need to count the number of "good arrays" of size
nwhere each element is in the range[1, m]and exactlykadjacent elements are equal. The solution involves combinatorial mathematics and modular arithmetic to efficiently compute the result, especially given the constraints wherenandmcan be as large as 105.Approach
Problem Analysis: The problem requires constructing arrays of length
nwith elements from1tomsuch that exactlykadjacent pairs (i.e.,arr[i-1] == arr[i]) exist. The solution leverages combinatorial mathematics to determine the number of valid arrays:mchoices.n-1adjac…