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
Candy Sharing Problem: Keep Maximum Unique FlavorsInput:candies = [1,2,1,3,2], k = 2Original candies:1213201234Unique flavors: {1, 2, 3}Total: 3 uniqueOptions for giving k=2 consecutive:• Give [1,2] (pos 0-1) → Keep [1,3,2] → 3 unique ✓• Give [2,1] (pos 1-2) → Keep [1,3,2] → 3 unique ✓• Give [1,3] (pos 2-3) → Keep [1,2,2] → 2 unique• Give [3,2] (pos 3-4) → Keep [1,2,1] → 2 uniqueOutput: 3 (maximum unique flavors we can keep)Colors: Red=Flavor1, Blue=Flavor2, Green=Flavor3
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
Asked in
Google 15 Amazon 12 Apple 8 Meta 6
8.4K Views
Medium Frequency
~15 min Avg. Time
245 Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen