mirror of
https://github.com/TheAlgorithms/C
synced 2024-11-25 06:49:36 +03:00
feat: add Frequency of the Most Frequent Element (#1195)
* add leetcode Frequency of the Most Frequent Element * Update 1838.c small fix * Update leetcode/src/1838.c Co-authored-by: David Leal <halfpacho@gmail.com>
This commit is contained in:
parent
60a0c5947d
commit
b819ddf3e6
@ -118,6 +118,7 @@
|
||||
| 1524 | [Number of Sub-arrays With Odd Sum](https://leetcode.com/problems/number-of-sub-arrays-with-odd-sum/) | [C](./src/1524.c) | Medium |
|
||||
| 1653 | [Minimum Deletions to Make String Balanced](https://leetcode.com/problems/minimum-deletions-to-make-string-balanced/) | [C](./src/1653.c) | Medium |
|
||||
| 1704 | [Determine if String Halves Are Alike](Determine if String Halves Are Alike) | [C](./src/1704.c) | Easy |
|
||||
| 1838 | [Frequency of the Most Frequent Element](https://leetcode.com/problems/frequency-of-the-most-frequent-element/) | [C](./src/1838.c) | Medium |
|
||||
| 1752 | [Check if Array Is Sorted and Rotated](https://leetcode.com/problems/check-if-array-is-sorted-and-rotated/) | [C](./src/1752.c) | Easy |
|
||||
| 2024 | [Maximize the Confusion of an Exam](https://leetcode.com/problems/maximize-the-confusion-of-an-exam/) | [C](./src/2024.c) | Medium |
|
||||
| 2095 | [Delete the Middle Node of a Linked List](https://leetcode.com/problems/delete-the-middle-node-of-a-linked-list/) | [C](./src/2095.c) | Medium |
|
||||
|
36
leetcode/src/1838.c
Normal file
36
leetcode/src/1838.c
Normal file
@ -0,0 +1,36 @@
|
||||
#define max(a,b) (((a)>(b))?(a):(b))
|
||||
|
||||
int compare(const int* i, const int* j)
|
||||
{
|
||||
return *i - *j;
|
||||
}
|
||||
|
||||
// Sort + prefix sum + windows sliding
|
||||
// Runtime: O(n*log(n))
|
||||
// Space: O(n)
|
||||
int maxFrequency(int* nums, int numsSize, int k){
|
||||
qsort(nums, numsSize, sizeof (int), (int(*) (const void*, const void*)) compare);
|
||||
long* prefixSum = malloc(numsSize * sizeof(long));
|
||||
|
||||
prefixSum[0] = nums[0];
|
||||
for(int i = 0; i < numsSize - 1; i++){
|
||||
prefixSum[i + 1] = prefixSum[i] + nums[i];
|
||||
}
|
||||
|
||||
int leftWindowPosition = 0;
|
||||
int result = 0;
|
||||
|
||||
for(int rightWindowPosition = 0; rightWindowPosition < numsSize; rightWindowPosition++){
|
||||
long rightSum = prefixSum[rightWindowPosition];
|
||||
long leftSum = prefixSum[leftWindowPosition];
|
||||
|
||||
while ((long)nums[rightWindowPosition] * (rightWindowPosition - leftWindowPosition) - (rightSum - leftSum) > k){
|
||||
leftWindowPosition += 1;
|
||||
}
|
||||
|
||||
result = max(result, rightWindowPosition - leftWindowPosition + 1);
|
||||
}
|
||||
|
||||
free(prefixSum);
|
||||
return result;
|
||||
}
|
Loading…
Reference in New Issue
Block a user