LeetCode Entry

3005. Count Elements With Maximum Frequency

08.03.2024 easy 2024 kotlin rust

Count of max-freq nums

3005. Count Elements With Maximum Frequency easy blog post substack youtube image.png

Join me on Telegram

https://t.me/leetcode_daily_unstoppable/532

Problem TLDR

Count of max-freq nums #easy

Intuition

Count frequencies, then filter by max and sum.

Approach

There are at most 100 elements, we can use array to count.

Complexity

  • Time complexity: \(O(n)\)

  • Space complexity: \(O(n)\)

Code


  fun maxFrequencyElements(nums: IntArray) = nums
  .asList().groupingBy { it }.eachCount().values.run {
    val max = maxOf { it }
    sumBy { if (it < max) 0 else it }
  }


  pub fn max_frequency_elements(nums: Vec<i32>) -> i32 {
    let mut freq = vec![0i32; 101];
    for x in nums { freq[x as usize] += 1; }
    let max = freq.iter().max().unwrap();
    freq.iter().filter(|&f| f == max).sum()
  }