forked from neetcode-gh/leetcode
-
Notifications
You must be signed in to change notification settings - Fork 0
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
Add 1838-frequency-of-the-most-frequent-element.c
- Loading branch information
Showing
1 changed file
with
34 additions
and
0 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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; | ||
} |