VOOZH about

URL: https://www.geeksforgeeks.org/dsa/maximum-number-of-fruits-in-two-baskets/

⇱ Longest Subarray with K Sections of Unique Items - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

Longest Subarray with K Sections of Unique Items

Last Updated : 20 May, 2025

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

  • Each element must fit into one of k sections.
  • Each section can only store a unique number and its multiple consecutive instances.

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.

Approach:

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:

  • Initialize left, right, and count to track the sliding window, along with a frequency map (mpp) to store element counts.
  • Iterate using right, adding elements to mpp, increasing count, and ensuring each element fits within the allowed k unique elements.
  • If the number of unique elements in mpp exceeds k, shrink the window by moving left and decreasing count.
  • Remove elements from mpp if their count becomes zero to maintain the valid unique element limit.
  • Continuously update maxCount whenever a valid window with k or fewer unique elements is found.
  • Expand the window by incrementing right until the entire array is processed.
  • Return maxCount, which stores the maximum number of elements.

Output
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.

Comment
Article Tags:
Article Tags: