Length of Longest Subarray With at Most K Frequency

As a Systems Engineer at Tata Consultancy Services, I deliver exceptional software products for mobile and web platforms, using agile methodologies and robust quality maintenance. I am experienced in performance testing, automation testing, API testing, and manual testing, with various tools and technologies such as Jmeter, Azure LoadTest, Selenium, Java, OOPS, Maven, TestNG, and Postman.
I have successfully developed and executed detailed test plans, test cases, and scripts for Android and web applications, ensuring high-quality standards and user satisfaction. I have also demonstrated my proficiency in manual REST API testing with Postman, as well as in end-to-end performance and automation testing using Jmeter and selenium with Java, TestNG and Maven. Additionally, I have utilized Azure DevOps for bug tracking and issue management.
You are given an integer array nums and an integer k.
The frequency of an element x is the number of times it occurs in an array.
An array is called good if the frequency of each element in this array is less than or equal to k.
Return the length of the longest good subarray of nums.
A subarray is a contiguous non-empty sequence of elements within an array.
LeetCode Problem - 2958
import java.util.HashMap;
import java.util.Map;
class Solution {
// Method to find the maximum length of a subarray with sum equals to k
public int maxSubarrayLength(int[] nums, int k) {
// Initialize variables to store the result and left index of the subarray
int result = 0, l = 0;
// Create a HashMap to store the frequency of elements
Map<Integer, Integer> map = new HashMap<>();
// Traverse the array
for (int i = 0; i < nums.length; i++) {
// Update the frequency of the current element in the map
map.put(nums[i], map.getOrDefault(nums[i], 0) + 1);
// Check if the frequency of any element exceeds k
while (map.get(nums[i]) > k) {
// Decrease the frequency of the leftmost element and move the left index to the right
map.put(nums[l], map.getOrDefault(nums[l], 0) - 1);
l++;
}
// Update the result with the maximum subarray length
result = Math.max(result, i - l + 1);
}
// Return the maximum subarray length
return result;
}
}




