Skip to content

Commit edb3382

Browse files
authored
Create 3318. Find X-Sum of All K-Long Subarrays I (#926)
2 parents d859c7a + e0d2c9e commit edb3382

File tree

1 file changed

+53
-0
lines changed

1 file changed

+53
-0
lines changed
Lines changed: 53 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,53 @@
1+
class Solution {
2+
public:
3+
int find(map<int, int>& mp, int x){
4+
// Max-heap to store {frequency, number}
5+
priority_queue<pair<int, int>> pq;
6+
// Build the heap from the frequency map
7+
for(auto it: mp){
8+
pq.push({it.second, it.first});
9+
}
10+
int sum=0;
11+
// Get the top x most frequent elements
12+
while(x-- && !pq.empty()){
13+
auto it = pq.top();
14+
pq.pop();
15+
int freq = it.first;
16+
// Add all occurrences of this number to the sum
17+
while(freq--){
18+
sum+=it.second;
19+
}
20+
}
21+
return sum;
22+
}
23+
vector<int> findXSum(vector<int>& nums, int k, int x) {
24+
// Frequency map for the current window
25+
map<int, int> mp;
26+
// Result vector
27+
vector<int> v;
28+
// Sliding window pointers
29+
int l=0, r=0;
30+
while(r<nums.size()){
31+
// Expand window: add right element
32+
mp[nums[r]]++;
33+
// Shrink window if size > k
34+
while(l<r && r-l+1 > k){
35+
// Remove left element from map
36+
mp[nums[l]]--;
37+
// Erase from map if frequency is 0
38+
if(mp[nums[l]] == 0){
39+
mp.erase(nums[l]);
40+
}
41+
// Move left pointer
42+
l++;
43+
}
44+
// If window is exactly size k, process it
45+
if(r-l+1 == k){
46+
v.push_back(find(mp, x));
47+
}
48+
// Move right pointer
49+
r++;
50+
}
51+
return v;
52+
}
53+
};

0 commit comments

Comments
 (0)