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: 1
💡 Note: Must give away 2 consecutive candies from [1,2,3]. Giving [1,2] keeps [3] with 1 unique flavor, giving [2,3] keeps [1] with 1 unique flavor. Maximum is 1.

Constraints

  • 1 ≤ candies.length ≤ 105
  • 1 ≤ k ≤ candies.length
  • 1 ≤ candies[i] ≤ 105

Visualization

Tap to expand
Number of Unique Flavors After Sharing K Candies INPUT candies array (flavors) 1 i=0 2 i=1 1 i=2 3 i=3 2 i=4 k = 2 (candies to share) Sister gets k=2 consecutive Window of size 2 slides through array ALGORITHM STEPS 1 Count All Flavors Total unique: {1,2,3} = 3 2 Init First Window Give [1,2], keep [1,3,2] 3 Slide Window Try each k-consecutive 4 Track Maximum Max unique kept = 3 Window Positions: [1,2],1,3,2 --> keep 3 1,[2,1],3,2 --> keep 2 1,2,[1,3],2 --> keep 2 1,2,1,[3,2] --> keep 2 Best: Window 1, keep 3 FINAL RESULT Optimal sharing strategy: Sister gets (first 2): 1 2 You keep (remaining): 1 3 2 Unique: {1, 2, 3} OUTPUT 3 Max unique flavors OK - Verified Key Insight: Use Sliding Window + HashMap: First count all unique flavors. Initialize by removing first k candies from your count. Then slide the window: add back the candy leaving the window, remove the candy entering. Track maximum unique flavors you keep. Time: O(n), Space: O(n) for the frequency map. TutorialsPoint - Number of Unique Flavors After Sharing K Candies | Optimal Solution
Asked in
Google 15 Amazon 12 Apple 8 Meta 6
8.5K 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