Skip to content

Commit 66c0920

Browse files
committed
Sync LeetCode submission Runtime - 0 ms (100.00%), Memory - 17.6 MB (97.86%)
1 parent 19816e4 commit 66c0920

File tree

2 files changed

+56
-0
lines changed

2 files changed

+56
-0
lines changed
Lines changed: 32 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,32 @@
1+
<p>You are given an array <code>nums</code> consisting of <strong>positive</strong> integers.</p>
2+
3+
<p>Return <em>the <strong>total frequencies</strong> of elements in</em><em> </em><code>nums</code>&nbsp;<em>such that those elements all have the <strong>maximum</strong> frequency</em>.</p>
4+
5+
<p>The <strong>frequency</strong> of an element is the number of occurrences of that element in the array.</p>
6+
7+
<p>&nbsp;</p>
8+
<p><strong class="example">Example 1:</strong></p>
9+
10+
<pre>
11+
<strong>Input:</strong> nums = [1,2,2,3,1,4]
12+
<strong>Output:</strong> 4
13+
<strong>Explanation:</strong> The elements 1 and 2 have a frequency of 2 which is the maximum frequency in the array.
14+
So the number of elements in the array with maximum frequency is 4.
15+
</pre>
16+
17+
<p><strong class="example">Example 2:</strong></p>
18+
19+
<pre>
20+
<strong>Input:</strong> nums = [1,2,3,4,5]
21+
<strong>Output:</strong> 5
22+
<strong>Explanation:</strong> All elements of the array have a frequency of 1 which is the maximum.
23+
So the number of elements in the array with maximum frequency is 5.
24+
</pre>
25+
26+
<p>&nbsp;</p>
27+
<p><strong>Constraints:</strong></p>
28+
29+
<ul>
30+
<li><code>1 &lt;= nums.length &lt;= 100</code></li>
31+
<li><code>1 &lt;= nums[i] &lt;= 100</code></li>
32+
</ul>
Lines changed: 24 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,24 @@
1+
# Approach 3: One-Pass Sum Max Frequencies
2+
3+
# Time: O(n)
4+
# Space: O(n)
5+
6+
class Solution:
7+
def maxFrequencyElements(self, nums: List[int]) -> int:
8+
freq = {}
9+
max_freq = 0
10+
total_freq = 0
11+
12+
for num in nums:
13+
freq[num] = freq.get(num, 0) + 1
14+
curr_freq = freq[num]
15+
16+
if curr_freq > max_freq:
17+
max_freq = curr_freq
18+
total_freq = curr_freq
19+
20+
elif curr_freq == max_freq:
21+
total_freq += curr_freq
22+
23+
return total_freq
24+

0 commit comments

Comments
 (0)