Distribute Candies - Problem
Candy Distribution Problem

Alice has collected n candies of various types, where each candy is represented by candyType[i]. However, her doctor has advised her to eat only half of her candies (n/2) to maintain her health.

Alice wants to maximize her candy-eating experience by consuming the maximum number of different candy types while following her doctor's advice. Given an integer array candyType of length n (where n is always even), return the maximum number of different types of candies Alice can eat if she only eats n/2 of them.

Example: If Alice has 6 candies of types [1,1,2,2,3,3], she can eat 3 candies. To maximize variety, she should pick one candy of each type (1, 2, and 3), giving her 3 different types.

Input & Output

example_1.py โ€” Basic Case
$ Input: [1,1,2,2,3,3]
โ€บ Output: 3
๐Ÿ’ก Note: Alice has 6 candies with 3 different types. She can eat 6/2 = 3 candies. Since there are exactly 3 unique types, she can eat one of each type to maximize variety.
example_2.py โ€” Limited by Candy Count
$ Input: [1,1,2,3]
โ€บ Output: 2
๐Ÿ’ก Note: Alice has 4 candies with 3 different types. She can only eat 4/2 = 2 candies. Even though there are 3 unique types, she's limited to eating only 2 different types.
example_3.py โ€” All Same Type
$ Input: [6,6,6,6]
โ€บ Output: 1
๐Ÿ’ก Note: Alice has 4 candies but they're all the same type. She can eat 4/2 = 2 candies, but since there's only 1 unique type, she can only experience 1 different candy type.

Constraints

  • n == candyType.length
  • 2 โ‰ค n โ‰ค 104
  • n is even
  • -105 โ‰ค candyType[i] โ‰ค 105

Visualization

Tap to expand
Alice's Candy Distribution StrategyStep 1: Count Unique Types4 different types foundStep 2: Check Eating LimitTotal candies: 8Can eat: 8/2 = 4Doctor's advice: max 4 candiesStep 3: Calculate Resultmin(4 types, 4 limit)= 4 different typesMaximum variety achieved!Example: [1,1,2,2,3,3,4,4]Input candies:11223344Alice's choice:1234Result: 4 different candy types - Perfect variety!
Understanding the Visualization
1
Survey the Options
Count how many different types of candies are available
2
Check Your Limit
Determine how many candies you're allowed to eat (n/2)
3
Maximize Variety
Take the minimum of available types and your eating limit
Key Takeaway
๐ŸŽฏ Key Insight: The answer is always min(unique_candy_types, n/2). Alice maximizes variety by choosing one candy from each unique type, limited by either available variety or eating constraint.
Asked in
Google 15 Amazon 12 Microsoft 8 Meta 6
78.3K Views
Medium Frequency
~15 min Avg. Time
2.8K 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