diff --git a/leetcode/DIRECTORY.md b/leetcode/DIRECTORY.md index da68aa6a..195140b4 100644 --- a/leetcode/DIRECTORY.md +++ b/leetcode/DIRECTORY.md @@ -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 | diff --git a/leetcode/src/1838.c b/leetcode/src/1838.c new file mode 100644 index 00000000..fe4469bf --- /dev/null +++ b/leetcode/src/1838.c @@ -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; +}