3321. Find X-Sum of All K-Long Subarrays II #2383
-
|
Topics: You are given an array The x-sum of an array is calculated by the following procedure:
Note that if an array has less than x distinct elements, its x-sum is the sum of the array. Return an integer array Example 1:
Example 2:
Constraints:
Hint:
Footnotes
|
Beta Was this translation helpful? Give feedback.
Replies: 1 comment 2 replies
-
|
We need to compute the x-sum for all contiguous subarrays of length The key challenge is to efficiently maintain and update the frequencies of elements as we slide the window of size Approach:We can use a sliding window technique combined with a frequency map and two heaps (or priority queues) to efficiently maintain the top
However, updating the heap for every window slide can be inefficient if done naively. Instead, we can:
Algorithm
Complexity
Let's implement this solution in PHP: 3321. Find X-Sum of All K-Long Subarrays II <?php
/**
* @param Integer[] $nums
* @param Integer $k
* @param Integer $x
* @return Integer[]
*/
function findXSum($nums, $k, $x) {
$n = count($nums);
$result = [];
$freq = [];
for ($i = 0; $i < $k; $i++) {
$freq[$nums[$i]] = isset($freq[$nums[$i]]) ? $freq[$nums[$i]] + 1 : 1;
}
for ($i = 0; $i <= $n - $k; $i++) {
$heap = new SplMaxHeap();
foreach ($freq as $num => $count) {
if ($count > 0) {
$heap->insert([$count, $num]);
}
}
$sum = 0;
$take = min($x, $heap->count());
for ($j = 0; $j < $take; $j++) {
list($count, $num) = $heap->extract();
$sum += $count * $num;
}
$result[] = $sum;
if ($i < $n - $k) {
$freq[$nums[$i]]--;
$freq[$nums[$i + $k]] = isset($freq[$nums[$i + $k]]) ? $freq[$nums[$i + $k]] + 1 : 1;
}
}
return $result;
}
// Test cases
print_r(findXSum([1,1,2,2,3,4,2,3], 6, 2)); // Output: [6,10,12]
print_r(findXSum([3,8,7,8,7,5], 2, 2)); // Output: [11,15,15,15,12]
?>Explanation:
|
Beta Was this translation helpful? Give feedback.
We need to compute the x-sum for all contiguous subarrays of length
kin the given arraynums. The x-sum is defined as the sum of the topxmost frequent elements in the subarray, where ties are broken by the larger element value. If there are fewer thanxdistinct elements, we simply sum all elements in the subarray.The key challenge is to efficiently maintain and update the frequencies of elements as we slide the window of size
kacross the array. A brute-force approach would be too slow for large inputs (up to 10^5), so we need an optimized solution.Approach:
We can use a sliding window technique combined with a frequency map and two heaps (or priority queues) to efficiently maintain…