Number of Unique Flavors After Sharing K Candies - Problem
You are given a 0-indexed integer array candies, where candies[i] represents the flavor of the i-th candy.
Your mom wants you to share these candies with your little sister by giving her k consecutive candies, but you want to keep as many unique flavors of candies as possible.
Return the maximum number of unique flavors of candy you can keep after sharing with your sister.
Input & Output
Example 1 — Basic Case
$
Input:
candies = [1,2,1,3,2], k = 2
›
Output:
3
💡 Note:
Give sister candies [1,2] (positions 0-1), [2,1] (positions 1-2), or [1,3] (positions 2-3), or [3,2] (positions 3-4). Best choice is any that keeps all 3 unique flavors {1,2,3}.
Example 2 — All Same Flavors
$
Input:
candies = [1,1,1,1], k = 2
›
Output:
1
💡 Note:
No matter which 2 consecutive candies we give away, we always keep flavor 1, so answer is 1 unique flavor.
Example 3 — Must Lose Unique Flavor
$
Input:
candies = [1,2,3], k = 2
›
Output:
2
💡 Note:
Must give away 2 consecutive candies from [1,2,3]. Giving [1,2] keeps {3}, giving [2,3] keeps {1}. Maximum is 1, but we can give [1,2] and keep [3], or give [2,3] and keep [1]. Wait, let me recalculate: give [1,2] keeps [3] = 1 unique, give [2,3] keeps [1] = 1 unique. Actually answer should be 1.
Constraints
- 1 ≤ candies.length ≤ 105
- 1 ≤ k ≤ candies.length
- 1 ≤ candies[i] ≤ 105
Visualization
Tap to expand
Understanding the Visualization
1
Input
Array of candy flavors and k consecutive candies to share
2
Process
Find which k consecutive candies to remove to keep most unique flavors
3
Output
Maximum number of unique flavors you can keep
Key Takeaway
🎯 Key Insight: Find the k consecutive candies whose removal loses the fewest unique flavors
💡
Explanation
AI Ready
💡 Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code