Created
October 21, 2025 18:38
-
-
Save tatsuyax25/c975d502c0838bce39980d397a3779cd to your computer and use it in GitHub Desktop.
You are given an integer array nums and two integers k and numOperations. You must perform an operation numOperations times on nums, where in each operation you: Select an index i that was not selected in any previous operations.
Add an integer in
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| /** | |
| * @param {number[]} nums - The input array of integers | |
| * @param {number} k - The maximum value that can be added/subtracted in one operation | |
| * @param {number} numOperations - The total number of operations allowed | |
| * @return {number} - The maximum frequency of any element after operations | |
| */ | |
| var maxFrequency = function(nums, k, numOperations) { | |
| const n = nums.length; | |
| // Sort the array to enable binary search and range grouping | |
| nums.sort((a, b) => a - b); | |
| // Precompute frequency of each number in the original array | |
| const freq = new Map(); | |
| for (const num of nums) { | |
| freq.set(num, (freq.get(num) || 0) + 1); | |
| } | |
| let maxFreq = 0; | |
| // Try every possible target value within the extended range | |
| for (let target = nums[0] - k; target <= nums[n - 1] + k; target++) { | |
| // Find the range of values that can be converted to 'target' using allowed operations | |
| const left = leftBound(nums, target - k); | |
| const right = rightBound(nums, target + k); | |
| // Total candidates in range: r - l + 1 | |
| // But we can only modify numOperations elements, so cap the frequency | |
| const currentFreq = Math.min(right - left + 1, (freq.get(target) || 0) + numOperations); | |
| maxFreq = Math.max(maxFreq, currentFreq); | |
| } | |
| return maxFreq; | |
| }; | |
| /** | |
| * Finds the leftmost index where nums[i] >= target | |
| * Equivalent to lower_bound in C++ | |
| */ | |
| function leftBound(nums, target) { | |
| let left = 0, right = nums.length - 1; | |
| while (left < right) { | |
| const mid = (left + right) >> 1; | |
| if (nums[mid] >= target) { | |
| right = mid; | |
| } else { | |
| left = mid + 1; | |
| } | |
| } | |
| return left; | |
| } | |
| /** | |
| * Finds the rightmost index where nums[i] <= target | |
| * Equivalent to upper_bound - 1 in C++ | |
| */ | |
| function rightBound(nums, target) { | |
| let left = 0, right = nums.length - 1; | |
| while (left < right) { | |
| const mid = (left + right + 1) >> 1; | |
| if (nums[mid] > target) { | |
| right = mid - 1; | |
| } else { | |
| left = mid; | |
| } | |
| } | |
| return left; | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment