|
| 1 | +/** |
| 2 | + * 3347. Maximum Frequency of an Element After Performing Operations II |
| 3 | + * https://leetcode.com/problems/maximum-frequency-of-an-element-after-performing-operations-ii |
| 4 | + * Difficulty: Hard |
| 5 | + * |
| 6 | + * You are given an integer array nums and two integers k and numOperations. |
| 7 | + * |
| 8 | + * You must perform an operation numOperations times on nums, where in each operation you: |
| 9 | + * - Select an index i that was not selected in any previous operations. |
| 10 | + * - Add an integer in the range [-k, k] to nums[i]. |
| 11 | + * |
| 12 | + * Return the maximum possible frequency of any element in nums after performing the operations. |
| 13 | + */ |
| 14 | + |
| 15 | +/** |
| 16 | + * @param {number[]} nums |
| 17 | + * @param {number} k |
| 18 | + * @param {number} numOperations |
| 19 | + * @return {number} |
| 20 | + */ |
| 21 | +var maxFrequency = function(nums, k, numOperations) { |
| 22 | + const n = nums.length; |
| 23 | + nums.sort((a, b) => a - b); |
| 24 | + |
| 25 | + const count = new Map(); |
| 26 | + for (const num of nums) { |
| 27 | + count.set(num, (count.get(num) || 0) + 1); |
| 28 | + } |
| 29 | + |
| 30 | + let result = 0; |
| 31 | + let left = 0; |
| 32 | + let right = 0; |
| 33 | + for (let mid = 0; mid < n; mid++) { |
| 34 | + while (nums[mid] - nums[left] > k) { |
| 35 | + left++; |
| 36 | + } |
| 37 | + |
| 38 | + while (right < n - 1 && nums[right + 1] - nums[mid] <= k) { |
| 39 | + right++; |
| 40 | + } |
| 41 | + |
| 42 | + const total = right - left + 1; |
| 43 | + result = Math.max( |
| 44 | + result, |
| 45 | + Math.min(total - count.get(nums[mid]), numOperations) + count.get(nums[mid]) |
| 46 | + ); |
| 47 | + } |
| 48 | + |
| 49 | + left = 0; |
| 50 | + for (right = 0; right < n; right++) { |
| 51 | + let mid = Math.floor((nums[left] + nums[right]) / 2); |
| 52 | + |
| 53 | + while (mid - nums[left] > k || nums[right] - mid > k) { |
| 54 | + left++; |
| 55 | + mid = Math.floor((nums[left] + nums[right]) / 2); |
| 56 | + } |
| 57 | + |
| 58 | + result = Math.max(result, Math.min(right - left + 1, numOperations)); |
| 59 | + } |
| 60 | + |
| 61 | + return result; |
| 62 | +}; |
0 commit comments