Easy To Understand Approach || Beats 100% ✅✅☑️☑️
\n# Steps to Solve the Problem\n1. Frequency Map:\n- Use an unordered map to count the frequency of elements in the current subarray of length k.\n2. Initial Wi
\n# Steps to Solve the Problem\n1. Frequency Map:\n- Use an unordered map to count the frequency of elements in the current subarray of length k.\n2. Initial Window:\n- Populate the frequency map for the first subarray (nums[0..k-1]).\n3. Calculate x-sum:\n\n- For the first window, determine the x-sum using the most frequent elements. If frequencies are tied, choose the larger value. Use a max heap for efficient retrieval of the top x elements.\n3. Sliding Window:\n\n-  Slide the window across the array:\nRemove the outgoing element from the frequency map.\nAdd the new incoming element.\nCalculate the x-sum for the updated window.\n4. Return Results:\n\n- Store the x-sums in a result vector and return it.\n\n# Complexity\n- Time complexity: O(n\u22C5klogk)\n- Space complexity: O(n+k)\n\n# Code\n```cpp []\nclass Solution {\npublic:\n    vector<int> findXSum(vector<int>& nums, int k, int x) \n    {\n        int n = nums.size();\n        vector<int> answer;\n        unordered_map<int, int> freq;\n\n        // Initialize frequency map for the first window\n        for (int j = 0; j < k; j++) {\n            freq[nums[j]]++;\n        }\n\n        // Calculate x-sum for the first window\n        answer.push_back(calculateXSum(freq, x));\n\n        // Slide the window\n        for (int i = 1; i <= n - k; i++) {\n            // Remove the element going out of the window\n            freq[nums[i - 1]]--;\n            if (freq[nums[i - 1]] == 0) {\n                freq.erase(nums[i - 1]);\n            }\n\n            // Add the new element coming into the window\n            freq[nums[i + k - 1]]++;\n\n            // Calculate x-sum for the current window\n            answer.push_back(calculateXSum(freq, x));\n        }\n        \n        return answer;\n    }\n\nprivate:\n    int calculateXSum(const unordered_map<int, int>& freq, int x) {\n        // Use a priority queue (max heap) to get the top x elements\n        priority_queue<pair<int, int>> pq; // (frequency, value)\n\n        for (const auto& entry : freq) {\n            pq.push({entry.second, entry.first});\n        }\n\n        int sum = 0;\n        for (int i = 0; i < x && !pq.empty(); i++) {\n            auto top = pq.top();\n            pq.pop();\n            sum += top.second * top.first; // sum = value * frequency\n        }\n\n        return sum;\n    }\n};\n\n```
['Hash Table', 'Heap (Priority Queue)', 'C++']