Skip to content

Commit cbd1c63

Browse files
authored
Merge pull request neetcode-gh#1840 from andynullwong/1838
Create 1838-frequency-of-the-most-frequent-element.js & .ts
2 parents 12e57ec + fdb2771 commit cbd1c63

File tree

2 files changed

+49
-0
lines changed

2 files changed

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

0 commit comments

Comments
 (0)