Skip to content

Commit f6bf24f

Browse files
committed
Add solution #1224
1 parent a71af03 commit f6bf24f

File tree

2 files changed

+49
-1
lines changed

2 files changed

+49
-1
lines changed

README.md

+2-1
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,4 @@
1-
# 1,186 LeetCode solutions in JavaScript
1+
# 1,187 LeetCode solutions in JavaScript
22

33
[https://leetcodejavascript.com](https://leetcodejavascript.com)
44

@@ -940,6 +940,7 @@
940940
1220|[Count Vowels Permutation](./solutions/1220-count-vowels-permutation.js)|Hard|
941941
1222|[Queens That Can Attack the King](./solutions/1222-queens-that-can-attack-the-king.js)|Medium|
942942
1223|[Dice Roll Simulation](./solutions/1223-dice-roll-simulation.js)|Hard|
943+
1224|[Maximum Equal Frequency](./solutions/1224-maximum-equal-frequency.js)|Hard|
943944
1232|[Check If It Is a Straight Line](./solutions/1232-check-if-it-is-a-straight-line.js)|Easy|
944945
1233|[Remove Sub-Folders from the Filesystem](./solutions/1233-remove-sub-folders-from-the-filesystem.js)|Medium|
945946
1249|[Minimum Remove to Make Valid Parentheses](./solutions/1249-minimum-remove-to-make-valid-parentheses.js)|Medium|
+47
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,47 @@
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

Comments
 (0)