Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
Skip to content

Commit 6534d68

Browse files
authored
Create 2598. Length Of Longest Subarray with at most K Frequency
1 parent 0c84195 commit 6534d68

File tree

1 file changed

+32
-0
lines changed

1 file changed

+32
-0
lines changed
Lines changed: 32 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,32 @@
1+
//Time Complexity - O(N)
2+
//Space Complexity : O(N)
3+
4+
class Solution {
5+
public int maxSubarrayLength(int[] nums, int k) {
6+
int start = 0, end = 0, result = 1;
7+
Map<Integer, Integer> freq = new HashMap<>();
8+
9+
while(end < nums.length) {
10+
int currentFreq = freq.getOrDefault(nums[end], 0);
11+
12+
if(currentFreq < k) {
13+
freq.put(nums[end], currentFreq+1);
14+
}
15+
else {
16+
while(nums[start] != nums[end]) {
17+
freq.put(nums[start], freq.get(nums[start])-1);
18+
start++;
19+
}
20+
start++;
21+
}
22+
23+
int newWindowLength = end-start+1;
24+
result = Math.max(result, newWindowLength);
25+
26+
end++;
27+
28+
}
29+
30+
return result;
31+
}
32+
}

0 commit comments

Comments
 (0)