Skip to content

Commit

Permalink
Merge pull request neetcode-gh#2156 from seinlin/1838
Browse files Browse the repository at this point in the history
Add 1838-frequency-of-the-most-frequent-element.c
  • Loading branch information
a93a authored Jan 27, 2023
2 parents 7d8d654 + af0ed98 commit efdf11e
Showing 1 changed file with 34 additions and 0 deletions.
34 changes: 34 additions & 0 deletions c/1838-frequency-of-the-most-frequent-element.c
Original file line number Diff line number Diff line change
@@ -0,0 +1,34 @@
int greater(const void *a, const void *b) {
return *(int*)a - *(int*)b;
}

int maxFrequency(int* nums, int numsSize, int k){
int left, right;
long sum = 0;
qsort(nums, numsSize, sizeof(int), greater);

//
// Exapmle;
// nums = [2, 3, 1, 4], k = 3
//
// After the array is sorted
// ------
// X X X O
// X X O O
// X O O O
// O O O O
// ------
// 'O' represents the value of the array.
// 'X' represents the value added by each operation.
// Just need to find the longer interval where the number of 'X'
// is less than or equal to k.
//

for (right = 0, left = 0; right < numsSize; right++) {
sum += nums[right];
if ((long)(right - left + 1) * nums[right] - sum > k) {
sum -= nums[left++];
}
}
return right - left;
}

0 comments on commit efdf11e

Please sign in to comment.