Find X-Sum of All K-Long Subarrays I - 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
xmost 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: 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].
Input & Output
Example 1 — Basic Case
$
Input:
nums = [3,2,3,1], k = 3, x = 2
›
Output:
[8,5]
💡 Note:
For subarray [3,2,3]: frequencies are {3:2, 2:1}. Since x=2, take all elements: 3×2 + 2×1 = 8. For subarray [2,3,1]: frequencies are {2:1, 3:1, 1:1}. Take top 2 by frequency,value: 3×1 + 2×1 = 5.
Example 2 — Less Than X Elements
$
Input:
nums = [1,1,2], k = 2, x = 4
›
Output:
[2,3]
💡 Note:
For subarray [1,1]: only 1 distinct element < x=4, so sum all: 1+1 = 2. For subarray [1,2]: only 2 distinct elements < x=4, so sum all: 1+2 = 3.
Example 3 — Tiebreaker by Value
$
Input:
nums = [2,4,2,4], k = 4, x = 2
›
Output:
[12]
💡 Note:
Subarray [2,4,2,4] has frequencies {2:2, 4:2}. Both have same frequency, so tiebreaker by value: take 4 (bigger) and 2. Sum: 4×2 + 2×2 = 12.
Constraints
- 1 ≤ n ≤ 50
- 1 ≤ nums[i] ≤ 50
- 1 ≤ k ≤ n
- 1 ≤ x ≤ k
Visualization
Tap to expand
Understanding the Visualization
1
Input
Array nums=[3,2,3,1], k=3, x=2
2
Process
For each subarray: count frequencies, sort, take top x
3
Output
Array of x-sums: [8,5]
Key Takeaway
🎯 Key Insight: Efficiently count frequencies and use value as tiebreaker to find top x elements
💡
Explanation
AI Ready
💡 Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code