Skip to content

Commit 9651ded

Browse files
committed
1838-frequency-of-the-most-frequent-element.js
1 parent e2aab2b commit 9651ded

File tree

1 file changed

+27
-0
lines changed

1 file changed

+27
-0
lines changed
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,27 @@
1+
/**
2+
* @param {number[]} nums
3+
* @param {number} k
4+
* @return {number}
5+
*/
6+
var maxFrequency = function (nums, k) {
7+
const sortedNums = nums.sort((a, b) => a - b);
8+
9+
let maxLength = 0;
10+
11+
let currentSum = 0;
12+
let leftWindow = 0;
13+
for (let rightWindow = 0; rightWindow < sortedNums.length; rightWindow++) {
14+
const currentLength = rightWindow - leftWindow + 1;
15+
const rightNum = sortedNums[rightWindow];
16+
currentSum += rightNum;
17+
18+
if (currentSum + k >= rightNum * currentLength) {
19+
maxLength = currentLength;
20+
} else {
21+
const leftNum = sortedNums[leftWindow];
22+
currentSum -= leftNum;
23+
leftWindow++;
24+
}
25+
}
26+
return maxLength;
27+
};

0 commit comments

Comments
 (0)