Skip to content

Instantly share code, notes, and snippets.

@tatsuyax25
Created October 22, 2025 16:37
Show Gist options
  • Select an option

  • Save tatsuyax25/9a1ffa041929fcf065d49175bc5b07ef to your computer and use it in GitHub Desktop.

Select an option

Save tatsuyax25/9a1ffa041929fcf065d49175bc5b07ef 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
/**
* @param {number[]} nums
* @param {number} k
* @param {number} numOperations
* @return {number}
*/
var maxFrequency = function (nums, k, numOperations) {
// Sort the array to enable binary search and range grouping
nums.sort((a, b) => a - b);
let maxFreq = 0;
const numCount = new Map(); // Stores frequency of each unique number
const candidateModes = new Set(); // Stores potential target values to maximize frequency
// Helper to add a value and its ±k neighbors as frequency targets
const addMode = (value) => {
candidateModes.add(value);
if (value - k >= nums[0]) candidateModes.add(value - k);
if (value + k <= nums[nums.length - 1]) candidateModes.add(value + k);
};
// Count frequency of each unique number and collect candidate modes
let start = 0;
for (let i = 0; i < nums.length; i++) {
if (nums[i] !== nums[start]) {
const count = i - start;
numCount.set(nums[start], count);
maxFreq = Math.max(maxFreq, count);
addMode(nums[start]);
start = i;
}
}
// Handle the final group
const finalCount = nums.length - start;
numCount.set(nums[start], finalCount);
maxFreq = Math.max(maxFreq, finalCount);
addMode(nums[start]);
// Binary search: find leftmost index ≥ value
const leftBound = (value) => {
let left = 0, right = nums.length - 1;
while (left < right) {
const mid = Math.floor((left + right) / 2);
if (nums[mid] < value) left = mid + 1;
else right = mid;
}
return left;
};
// Binary search: find rightmost index ≤ value
const rightBound = (value) => {
let left = 0, right = nums.length - 1;
while (left < right) {
const mid = Math.floor((left + right + 1) / 2);
if (nums[mid] > value) right = mid - 1;
else left = mid;
}
return left;
};
// Try each candidate mode and compute max frequency achievable
for (const mode of candidateModes) {
const left = leftBound(mode - k);
const right = rightBound(mode + k);
const rangeSize = right - left + 1;
// If mode already exists, we can boost its count
const baseCount = numCount.get(mode) || 0;
const possibleFreq = Math.min(rangeSize, baseCount + numOperations);
maxFreq = Math.max(maxFreq, possibleFreq);
}
return maxFreq;
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment