3318. Find X-Sum of All K-Long Subarrays I #2379
-
|
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 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 calculate the x-sum for every contiguous subarray of length Approach
Let's implement this solution in PHP: 3318. Find X-Sum of All K-Long Subarrays I <?php
/**
* @param Integer[] $nums
* @param Integer $k
* @param Integer $x
* @return Integer[]
*/
function findXSum($nums, $k, $x) {
$n = count($nums);
$result = array();
for ($i = 0; $i <= $n - $k; $i++) {
$window = array_slice($nums, $i, $k);
$freq = array();
foreach ($window as $num) {
if (!isset($freq[$num])) {
$freq[$num] = 0;
}
$freq[$num]++;
}
$distinct = array_keys($freq);
usort($distinct, function($a, $b) use ($freq) {
if ($freq[$a] == $freq[$b]) {
return $b - $a;
}
return $freq[$b] - $freq[$a];
});
$topX = array_slice($distinct, 0, $x);
$sum = 0;
foreach ($window as $num) {
if (in_array($num, $topX)) {
$sum += $num;
}
}
$result[] = $sum;
}
return $result;
}
// Test cases
// Example 1
$nums = array(1, 1, 2, 2, 3, 4, 2, 3);
$k = 6;
$x = 2;
print_r(findXSum($nums, $k, $x));
// Output: [6, 10, 12]
// Example 2
$nums = array(3, 8, 7, 8, 7, 5);
$k = 2;
$x = 2;
print_r(findXSum($nums, $k, $x));
// Output: [11, 15, 15, 15, 12]
?>Explanation:
|
Beta Was this translation helpful? Give feedback.
We need to calculate the x-sum for every contiguous subarray of length
kin the given arraynums. The x-sum of an array is defined as the sum of all elements that belong to the topxmost frequent elements. If there are ties in frequency, the element with the larger value is considered more frequent. If there are fewer thanxdistinct elements, the x-sum is simply the sum of all elements in the subarray.Approach
kto iterate through all possible subarrays of lengthkinnums.