Last active
June 11, 2025 12:01
-
-
Save puranik3/25116650a9211d7ab0c04bea7b711afe to your computer and use it in GitHub Desktop.
2958. Length of Longest Subarray With at Most K Frequency
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import java.util.HashMap; | |
class Solution { | |
public int maxSubarrayLength(int[] nums, int k) { | |
int N = nums.length; | |
int left = 0, right = 0, f, x; | |
int result = 1, cur; | |
HashMap<Integer, Integer> freq = new HashMap<>(); | |
while ( left <= right && right < N ) { | |
x = nums[right]; | |
if ( freq.containsKey( x ) ) { | |
f = freq.get( x ); | |
if ( f == k ) { | |
result = Math.max( result, right - left ); | |
// @todo Improve TC by maintaining a linked list (of max length k) for each unique array item which has the previous k indexes where the item occured | |
while ( nums[left] != nums[right] ) { | |
freq.put( nums[left], freq.get( nums[left] ) - 1 ); | |
++left; | |
} | |
++left; | |
} else { | |
freq.put( x, 1 + f ); | |
} | |
} else { | |
freq.put( x, 1 ); | |
} | |
++right; | |
} | |
cur = right - left; | |
if ( cur > result ) { | |
result = cur; | |
} | |
return result; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment