Skip to content

Commit

Permalink
feature: frequency of the most frequent element
Browse files Browse the repository at this point in the history
  • Loading branch information
solairerove committed Nov 18, 2023
1 parent beb7af0 commit 6c66601
Show file tree
Hide file tree
Showing 2 changed files with 35 additions and 0 deletions.
17 changes: 17 additions & 0 deletions sliding_window/FrequencyOfTheMostFrequentElement.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,17 @@
from typing import List


# O(n * log(n)) time | O(log(n)) space
def max_frequency(self, nums: List[int], k: int) -> int:
nums.sort()
low, res, total = 0, 0, 0
for high in range(len(nums)):
total += nums[high]

while nums[high] * (high - low + 1) - total > k:
total -= nums[low]
low += 1

res = max(res, high - low + 1)

return res
18 changes: 18 additions & 0 deletions sliding_window/test/test_max_frequency.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,18 @@
import unittest

from sliding_window.FrequencyOfTheMostFrequentElement import max_frequency


class MyTestCase(unittest.TestCase):
def test_max_frequency(self):
self.assertEqual(3, max_frequency(self, nums=[1, 2, 4], k=5))

def test_max_frequency_1(self):
self.assertEqual(2, max_frequency(self, nums=[1, 4, 8, 13], k=5))

def test_max_frequency_2(self):
self.assertEqual(1, max_frequency(self, nums=[3, 9, 6], k=2))


if __name__ == '__main__':
unittest.main()

0 comments on commit 6c66601

Please sign in to comment.