-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathLength_of_Longest_Subarray_With_at_Most_K_Frequency.java
More file actions
58 lines (56 loc) · 1.6 KB
/
Length_of_Longest_Subarray_With_at_Most_K_Frequency.java
File metadata and controls
58 lines (56 loc) · 1.6 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
import java.util.*;
import java.io.*;
import java.lang.*;
public class Length_of_Longest_Subarray_With_at_Most_K_Frequency {
class Solution {
public int maxSubarrayLength(int[] nums, int k)
{
int n = nums.length;
HashMap<Integer, Integer> hm = new HashMap<>();
int max = 0;
int l = 0;
for (int r = 0 ; r < n ; r++)
{
hm.put(nums[r] , hm.getOrDefault(nums[r] , 0) + 1);
while (hm.get(nums[r]) > k)
{
hm.put(nums[l] , hm.get(nums[l]) - 1);
if(hm.get(nums[l]) == 0)
{
hm.remove(nums[l]);
}
l++;
}
int ans = r - l + 1;
max = Math.max(max , ans);
}
return max;
}
}
// class Solution {
// public int maxSubarrayLength(int[] nums, int k) {
// HashMap<Integer , Integer> hm = new HashMap<>();
// int n = nums.length;
// int max = 0;
// for(int i = 0 ; i<n ; i++)
// {
// int j;
// for(j = i ; j<n ; j++)
// {
// hm.put(nums[j] , hm.getOrDefault(nums[j] , 0) + 1);
// if(hm.get(nums[j]) > k)
// {
// break;
// }
// }
// int ans = j-i;
// if(ans>max)
// {
// max = ans;
// }
// hm.clear();
// }
// return max;
// }
// }
}