From e0d2c9e59c9c86833227d21d9f81cc70428b0a1b Mon Sep 17 00:00:00 2001 From: chayan das Date: Tue, 4 Nov 2025 15:32:42 +0530 Subject: [PATCH] Create 3318. Find X-Sum of All K-Long Subarrays I --- 3318. Find X-Sum of All K-Long Subarrays I | 53 ++++++++++++++++++++++ 1 file changed, 53 insertions(+) create mode 100644 3318. Find X-Sum of All K-Long Subarrays I diff --git a/3318. Find X-Sum of All K-Long Subarrays I b/3318. Find X-Sum of All K-Long Subarrays I new file mode 100644 index 0000000..769a66a --- /dev/null +++ b/3318. Find X-Sum of All K-Long Subarrays I @@ -0,0 +1,53 @@ +class Solution { +public: + int find(map& mp, int x){ + // Max-heap to store {frequency, number} + priority_queue> pq; + // Build the heap from the frequency map + for(auto it: mp){ + pq.push({it.second, it.first}); + } + int sum=0; + // Get the top x most frequent elements + while(x-- && !pq.empty()){ + auto it = pq.top(); + pq.pop(); + int freq = it.first; + // Add all occurrences of this number to the sum + while(freq--){ + sum+=it.second; + } + } + return sum; + } + vector findXSum(vector& nums, int k, int x) { + // Frequency map for the current window + map mp; + // Result vector + vector v; + // Sliding window pointers + int l=0, r=0; + while(r k + while(l k){ + // Remove left element from map + mp[nums[l]]--; + // Erase from map if frequency is 0 + if(mp[nums[l]] == 0){ + mp.erase(nums[l]); + } + // Move left pointer + l++; + } + // If window is exactly size k, process it + if(r-l+1 == k){ + v.push_back(find(mp, x)); + } + // Move right pointer + r++; + } + return v; + } +};