Skip to content

Commit 2e2dd50

Browse files
committed
Added the Solution for Frequency of the Most Frequent Element
1 parent e052949 commit 2e2dd50

File tree

2 files changed

+256
-1
lines changed

2 files changed

+256
-1
lines changed

dsa-problems/leetcode-problems/1800-1899.md

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -242,7 +242,7 @@ export const problems = [
242242
"problemName": "1838. Frequency of the Most Frequent Element",
243243
"difficulty": "Medium",
244244
"leetCodeLink": "https://leetcode.com/problems/frequency-of-the-most-frequent-element",
245-
"solutionLink": "#"
245+
"solutionLink": "/dsa-solutions/lc-solutions/1800-1899/frequency-of-the-most-frequent-element"
246246
},
247247
{
248248
"problemName": "1839. Longest Substring Of All Vowels in Order",
Lines changed: 255 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,255 @@
1+
---
2+
id: frequency-of-the-most-frequent-element
3+
title: Frequency of the Most Frequent Element
4+
sidebar_label: 1838 -Frequency of the Most Frequent Element
5+
tags:
6+
- Array
7+
- Binary Search
8+
- Greedy
9+
- Sliding Window
10+
- Sorting
11+
- Prefix Sum
12+
13+
description: "This is a solution to the Frequency of the Most Frequent Element problem on LeetCode."
14+
---
15+
16+
## Problem Description
17+
The frequency of an element is the number of times it occurs in an array.
18+
19+
You are given an integer array nums and an integer k. In one operation, you can choose an index of nums and increment the element at that index by 1.
20+
21+
Return the maximum possible frequency of an element after performing at most k operations.
22+
23+
### Examples
24+
25+
**Example 1:**
26+
27+
```
28+
Input: nums = [1,2,4], k = 5
29+
Output: 3
30+
Explanation: Increment the first element three times and the second element two times to make nums = [4,4,4].
31+
4 has a frequency of 3.
32+
33+
```
34+
35+
**Example 2:**
36+
```
37+
Input: nums = [1,4,8,13], k = 5
38+
Output: 2
39+
Explanation: There are multiple optimal solutions:
40+
- Increment the first element three times to make nums = [4,4,8,13]. 4 has a frequency of 2.
41+
- Increment the second element four times to make nums = [1,8,8,13]. 8 has a frequency of 2.
42+
- Increment the third element five times to make nums = [1,4,13,13]. 13 has a frequency of 2.
43+
```
44+
45+
**Example 3:**
46+
```
47+
Input: nums = [3,9,6], k = 2
48+
Output: 1
49+
```
50+
51+
### Constraints
52+
53+
- `1 <= nums.length <= 10^5`
54+
- `1 <= nums[i] <= 10^5`
55+
- `1 <= k <= 10^5`
56+
## Solution for Frequency of the Most Frequent Element Problem
57+
### Approach
58+
To determine the amount needed to convert the current sliding window [1, 2, 4] into [4, 4, 4], we use the formula (num_right×(right−left+1))−total, where num_right is the value we want to fill the window with (in this case, 4), right and left are the indices defining the window, and total is the sum of the current window. If this amount is within the budget k, i.e., (num_right×(right−left+1))−total≤k, then it is possible to achieve the desired frequency with a cost equal to the window length (right - left + 1).
59+
60+
#### Steps
61+
##### Sorting:
62+
- Sorting the array helps to bring similar values closer together. This makes it easier to increase the frequency of a number by making other numbers in the subarray equal to it with minimal increments.
63+
##### Sliding Window:
64+
65+
- The sliding window technique allows us to consider subarrays of the sorted array incrementally.
66+
- We maintain a window [i, j] where j is the current end of the window, and i is the start.
67+
##### Sum Calculation:
68+
- We keep a running sum of the elements within the window.
69+
- For each new element added to the window (i.e., extending j), we calculate the total number of operations needed to make all elements in the window equal to the current element nums[j].
70+
- This is checked using the formula (j−i+1)×nums[j]−sum. If this value is greater than k, it means we need more than k operations to make all elements equal to nums[j].
71+
##### Adjusting the Window:
72+
73+
- If the current window requires more than k operations, we shrink the window from the left by incrementing i until the condition is satisfied.
74+
- If the condition is satisfied, it means the current window can be made equal with at most k increments, and we update the maximum frequency (maxFreq) with the size of the current window.
75+
##### Result:
76+
- The maximum frequency (maxFreq) found during the iterations will be the result.
77+
78+
79+
<Tabs>
80+
<TabItem value="Solution" label="Solution">
81+
82+
#### Implementation
83+
```jsx live
84+
function Solution(arr) {
85+
function maxFrequency(nums, k) {
86+
nums.sort((a, b) => a - b);
87+
let maxFreq = 1;
88+
let i = 0;
89+
let sum = 0;
90+
91+
for (let j = 0; j < nums.length; j++) {
92+
sum += nums[j];
93+
while ((j - i + 1) * nums[j] - sum > k) {
94+
sum -= nums[i];
95+
i++;
96+
}
97+
maxFreq = Math.max(maxFreq, j - i + 1);
98+
}
99+
100+
return maxFreq;
101+
}
102+
const input = [1, 2 ,4];
103+
const k = 5
104+
const output = maxFrequency(input , k) ;
105+
return (
106+
<div>
107+
<p>
108+
<b>Input: </b>
109+
{JSON.stringify(input)}
110+
</p>
111+
<p>
112+
<b>Output:</b> {output.toString()}
113+
</p>
114+
</div>
115+
);
116+
}
117+
```
118+
119+
#### Complexity Analysis
120+
121+
- Time Complexity: $ O(nlogn) $ because of sorting, where n is the size of array
122+
- Space Complexity: $ O(1) $
123+
124+
## Code in Different Languages
125+
<Tabs>
126+
<TabItem value="JavaScript" label="JavaScript">
127+
<SolutionAuthor name="@hiteshgahanolia"/>
128+
```javascript
129+
function maxFrequency(nums, k) {
130+
nums.sort((a, b) => a - b);
131+
let maxFreq = 1;
132+
let i = 0;
133+
let sum = 0;
134+
135+
for (let j = 0; j < nums.length; j++) {
136+
sum += nums[j];
137+
while ((j - i + 1) * nums[j] - sum > k) {
138+
sum -= nums[i];
139+
i++;
140+
}
141+
maxFreq = Math.max(maxFreq, j - i + 1);
142+
}
143+
144+
return maxFreq;
145+
}
146+
```
147+
148+
</TabItem>
149+
<TabItem value="TypeScript" label="TypeScript">
150+
<SolutionAuthor name="@hiteshgahanolia"/>
151+
```typescript
152+
function maxFrequency(nums: number[], k: number): number {
153+
nums.sort((a, b) => a - b);
154+
let maxFreq = 1;
155+
let i = 0;
156+
let sum = 0;
157+
158+
for (let j = 0; j < nums.length; j++) {
159+
sum += nums[j];
160+
while ((j - i + 1) * nums[j] - sum > k) {
161+
sum -= nums[i];
162+
i++;
163+
}
164+
maxFreq = Math.max(maxFreq, j - i + 1);
165+
}
166+
167+
return maxFreq;
168+
}
169+
170+
```
171+
</TabItem>
172+
<TabItem value="Python" label="Python">
173+
<SolutionAuthor name="@hiteshgahanolia"/>
174+
```python
175+
class Solution:
176+
def maxFrequency(self, nums, k):
177+
nums.sort()
178+
maxFreq = 1
179+
i = 0
180+
sum = 0
181+
182+
for j in range(len(nums)):
183+
sum += nums[j]
184+
while (j - i + 1) * nums[j] - sum > k:
185+
sum -= nums[i]
186+
i += 1
187+
maxFreq = max(maxFreq, j - i + 1)
188+
189+
return maxFreq
190+
191+
```
192+
193+
</TabItem>
194+
<TabItem value="Java" label="Java">
195+
<SolutionAuthor name="@hiteshgahanolia"/>
196+
```java
197+
import java.util.Arrays;
198+
199+
public class Solution {
200+
public int maxFrequency(int[] nums, int k) {
201+
Arrays.sort(nums);
202+
long maxFreq = 1;
203+
long i = 0;
204+
long sum = 0;
205+
206+
for (long j = 0; j < nums.length; j++) {
207+
sum += nums[(int) j];
208+
while ((j - i + 1) * nums[(int) j] - sum > k) {
209+
sum -= nums[(int) i];
210+
i++;
211+
}
212+
maxFreq = Math.max(maxFreq, j - i + 1);
213+
}
214+
215+
return (int) maxFreq;
216+
}
217+
}
218+
219+
```
220+
221+
</TabItem>
222+
<TabItem value="C++" label="C++">
223+
<SolutionAuthor name="@hiteshgahanolia"/>
224+
```cpp
225+
class Solution {
226+
public:
227+
int maxFrequency(vector<int>& nums, int k) {
228+
sort(nums.begin(), nums.end());
229+
long maxFreq = 1;
230+
long i = 0;
231+
long j = 0;
232+
long long sum = 0;
233+
234+
while (j < nums.size()) {
235+
sum += nums[j];
236+
while ((j - i + 1) * nums[j] - sum > k) sum -= nums[i++];
237+
maxFreq =max(maxFreq, j-i+1);
238+
j++;
239+
}
240+
return maxFreq;
241+
}
242+
};
243+
```
244+
</TabItem>
245+
</Tabs>
246+
247+
</TabItem>
248+
</Tabs>
249+
250+
## References
251+
252+
- **LeetCode Problem**: [Frequency of the Most Frequent Element](https://leetcode.com/problems/frequency-of-the-most-frequent-element/description/)
253+
254+
- **Solution Link**: [LeetCode Solution](https://leetcode.com/problems/frequency-of-the-most-frequent-element/solution)
255+

0 commit comments

Comments
 (0)