Problem
You are given an array nums
of n
integers and two integers k
and x
.
The x-sum of an array is calculated by the following procedure:
- Count the occurrences of all elements in the array.
- Keep only the occurrences of the top
x
most frequent elements. If two elements have the same number of occurrences, the element with the bigger value is considered more frequent. - Calculate the sum of the resulting array.
Note that if an array has less than x
distinct elements, its x-sum is the sum of the array.
Return an integer array answer
of length n - k + 1
where answer[i]
is the x-sum of the subarray nums[i..i + k - 1]
.
Examples
Example 1
|
|
Example 2
|
|
Constraints
nums.length == n
1 <= n <= 10^5
1 <= nums[i] <= 10^9
1 <= x <= k <= nums.length
Solution
Method 1 – Sliding Window + Frequency Map + Heap (Optimized for Large n)
Intuition
For each k-length subarray, we want the sum of the x most frequent elements (with ties broken by larger value). Since n can be large, we need an efficient way to maintain frequencies as the window slides.
Approach
- Use a sliding window of size k over nums.
- Maintain a frequency map for the current window.
- For each window:
- Use a heap (max-heap by frequency, then value) to get the x most frequent elements.
- If there are fewer than x distinct elements, sum the whole window.
- Otherwise, sum the elements corresponding to the x most frequent elements (each counted as many times as they appear in the window).
- Slide the window and update the frequency map efficiently.
- Return the answer array.
Code
|
|
|
|
Complexity
- ⏰ Time complexity:
O(n * k log k)
, since for each window we sort up to k elements. - 🧺 Space complexity:
O(k)
, for the frequency map and heap.