![]() |
VOOZH | about |
You are given an array of positive integers arr[] and an integer k. The task is to find length of the longest subarray with the following conditions
Examples:
Input: arr[] = [1, 2, 2, 3, 1, 4], k = 2
Output: 3
Explanation: The subarray is [1, 2, 2, 3, 1], the sections are [1], [2, 2], [3] and [1]
Total elements chosen = 3.Input: arr[] = [4, 1, 1, 3, 2, 2], k = 3
Output: 5
Explanation: The subarray is [1, 1, 3, 2, 2], the sections are [1, 1], [3] and [2, 2]Input: arr[] = [5, 5, 5, 5, 5], k = 1
Output: 5
Explanation: All elements are 5, and k = 1, so all can be stored in one section.
The idea is to find the maximum number of elements that can be selected while ensuring that at most k unique elements exist at any time. Using the Sliding Window technique, we expand the window by adding elements and shrink it when the number of unique elements exceeds k. The frequency map helps track the count of elements, ensuring efficient updates. The observation is that instead of checking all possible selections, a dynamic window allows solving the problem efficiently in linear time.
Steps to implement the above idea:
3
Time Complexity: O(n), as each element is processed at most twice, once when added and once when removed.
Space Complexity: O(k), as the frequency map stores at most k unique elements at any time.