Problem Description
Given an array of candies (each represented by its flavor as an integer), you must share k consecutive candies with your sister and keep the rest. Your goal is to maximize the number of unique candy flavors you keep. In other words, choose a contiguous block of k candies to remove so that the remaining candies preserve as many distinct flavors as possible.
Key Insights
- Pre-calculate the total frequency of each flavor in the entire array.
- The overall count of unique flavors is fixed.
- For any contiguous block (window) of k candies, determine the number of flavors that are completely removed from the remaining candy collection (i.e., flavors for which the window count equals the total count).
- Slide the window over the array to find the block that minimizes the removal (loss) of unique flavors.
- The maximum unique flavors you can eat equals total unique flavors minus the minimal number of flavors lost by sharing.
Space and Time Complexity
Time Complexity: O(n), where n is the number of candies, because we pre-calculate frequencies and then slide a window across the array. Space Complexity: O(n) in the worst case due to storing frequency counts in hash maps/dictionaries.
Solution
We first compute a frequency dictionary (totalCounts) for all candies to know how many times each flavor appears. The total number of unique flavors is the count of keys in this dictionary.
Next, we use a sliding window of size k to simulate sharing k consecutive candies. For each window, we keep another frequency dictionary (windowCounts) that tracks the flavors in that window. For a given window, if for a flavor the count in windowCounts equals the count in totalCounts, it means that flavor is completely removed from the remaining candies. We want to choose the window with the least number of such completely removed flavors.
We update the window frequency counts as we slide the window and keep track of the loss (i.e. the number of flavors that are completely removed). Finally, the maximum unique flavors you can keep is calculated as: unique kept = total unique flavors - minimal loss
Key data structures and techniques:
- Two hash maps/dictionaries to store total and window frequencies.
- A sliding window to efficiently update the window frequency counts rather than recalculating from scratch.