|
| 1 | +/** |
| 2 | + * 1224. Maximum Equal Frequency |
| 3 | + * https://leetcode.com/problems/maximum-equal-frequency/ |
| 4 | + * Difficulty: Hard |
| 5 | + * |
| 6 | + * Given an array nums of positive integers, return the longest possible length of an array prefix |
| 7 | + * of nums, such that it is possible to remove exactly one element from this prefix so that every |
| 8 | + * number that has appeared in it will have the same number of occurrences. |
| 9 | + * |
| 10 | + * If after removing one element there are no remaining elements, it's still considered that every |
| 11 | + * appeared number has the same number of ocurrences (0). |
| 12 | + */ |
| 13 | + |
| 14 | +/** |
| 15 | + * @param {number[]} nums |
| 16 | + * @return {number} |
| 17 | + */ |
| 18 | +var maxEqualFreq = function(nums) { |
| 19 | + const countMap = new Map(); |
| 20 | + const freqMap = new Map(); |
| 21 | + let result = 0; |
| 22 | + |
| 23 | + for (let i = 0; i < nums.length; i++) { |
| 24 | + const num = nums[i]; |
| 25 | + const prevCount = countMap.get(num) || 0; |
| 26 | + const newCount = prevCount + 1; |
| 27 | + |
| 28 | + countMap.set(num, newCount); |
| 29 | + |
| 30 | + if (prevCount > 0) { |
| 31 | + freqMap.set(prevCount, (freqMap.get(prevCount) || 0) - 1); |
| 32 | + if (freqMap.get(prevCount) === 0) freqMap.delete(prevCount); |
| 33 | + } |
| 34 | + freqMap.set(newCount, (freqMap.get(newCount) || 0) + 1); |
| 35 | + |
| 36 | + if (freqMap.size === 1) { |
| 37 | + const [freq, occurrences] = [...freqMap.entries()][0]; |
| 38 | + if (freq === 1 || occurrences === 1) result = i + 1; |
| 39 | + } else if (freqMap.size === 2) { |
| 40 | + const freqs = [...freqMap.keys()].sort((a, b) => a - b); |
| 41 | + if (freqs[0] === 1 && freqMap.get(freqs[0]) === 1) result = i + 1; |
| 42 | + if (freqs[1] === freqs[0] + 1 && freqMap.get(freqs[1]) === 1) result = i + 1; |
| 43 | + } |
| 44 | + } |
| 45 | + |
| 46 | + return result; |
| 47 | +}; |
0 commit comments