Apply Operations to Maximize Frequency Score || JAVASCRIPT || Solution by Bharadwaj
Approach\nBinary Search with Prefix Sums\n\n# Complexity\n- Time complexity:\nO(nlogn)\n\n- Space complexity:\nO(n)\n\n# Code\n\n// Function to find the score b
# Approach\nBinary Search with Prefix Sums\n\n# Complexity\n- Time complexity:\nO(nlogn)\n\n- Space complexity:\nO(n)\n\n# Code\n```\n// Function to find the score between indices l and r in the nums array\nfunction find(l, r, nums, prefix) {\n    let mid = ~~((r + l) / 2);\n    let first = prefix[mid];\n\n    // Adjust the sum based on the prefix sum array\n    if (l > 0) {\n        first -= prefix[l - 1];\n    }\n\n    let ans = nums[mid] * (mid - l + 1) - first;\n    let second = prefix[r] - prefix[mid];\n    ans += second - nums[mid] * (r - mid);\n    return ans;\n}\n\n// Function to calculate the maximum frequency score\nfunction maxFrequencyScore(nums, k) {\n    nums.sort((a, b) => a - b);\n    let n = nums.length;\n    let prefix = new Array(n).fill(0);\n\n    // Create a prefix sum array\n    for (let i = 0; i < n; ++i) {\n        prefix[i] = (i === 0) ? nums[i] : nums[i] + prefix[i - 1];\n    }\n\n    let max = 0;\n    for (let i = 0; i < n; ++i) {\n        let low = i;\n        let high = n - 1;\n        let res = -1;\n\n        // Binary search to find the rightmost index satisfying the condition\n        while (low <= high) {\n            let mid = Math.floor(low + (high - low) / 2);\n            if (find(i, mid, nums, prefix) <= k) {\n                res = mid;\n                low = mid + 1;\n            } else {\n                high = mid - 1;\n            }\n        }\n\n        // Update the maximum length of subarray\n        if (res !== -1) {\n            max = Math.max(max, res - i + 1);\n        }\n    }\n    return max;\n}\n```
['JavaScript']