Sort + Sliding Window | Well Explained
\n# Code\n\nclass Solution {\npublic:\n    // Function to calculate the maximum frequency score within a given budget \'k\'\n    int maxFrequencyScore(vector<in
![image.png](https://assets.leetcode.com/users/images/0a1d68e7-bd53-4fff-b885-95a7b51536fc_1710223267.6374302.png)\n# Code\n```\nclass Solution {\npublic:\n    // Function to calculate the maximum frequency score within a given budget \'k\'\n    int maxFrequencyScore(vector<int>& nums, long long k) { \n        // Fast I/O optimization for better performance\n        ios_base::sync_with_stdio(0), cin.tie(0), cout.tie(0);\n        \n        // Sorting the input array to simplify the frequency score calculation\n        sort(nums.begin(), nums.end());\n\n        // Initialize pointers and variables for array size and answer\n        int i = 0, j = 0, n = nums.size(), ans = 0;\n\n        // Loop through the array using two pointers (i and j)\n        while (j < n) {\n            // Update \'k\' by subtracting the difference between the current and median elements\n            k -= nums[j] - nums[(j + i) / 2];\n\n            // Adjust the median element and move the left pointer \'i\' until \'k\' becomes non-negative\n            while (k < 0 && i <= j) {\n                k += nums[(i + j + 1) / 2] - nums[i++];\n            }\n\n            // Update the answer with the current subarray length\n            ans = max(ans, j - i + 1);\n\n            // Move the right pointer \'j\' to extend the subarray\n            j++;\n        } \n\n        // Return the maximum frequency score within the given budget\n        return ans;\n    }\n};\n```
['Array', 'Sliding Window', 'Sorting', 'C++']