Distribute Candies - Problem

Alice has n candies, where the i-th candy is of type candyType[i]. Alice noticed that she started to gain weight, so she visited a doctor.

The doctor advised Alice to only eat n / 2 of the candies she has (n is always even). Alice likes her candies very much, and she wants to eat the maximum number of different types of candies while still following the doctor's advice.

Given the integer array candyType of length n, return the maximum number of different types of candies she can eat if she only eats n / 2 of them.

Input & Output

Example 1 — Basic Case
$ Input: candyType = [1,1,2,2,3,3]
Output: 3
💡 Note: There are 3 unique candy types (1, 2, 3). Alice can eat 6/2 = 3 candies, so she can eat all 3 different types.
Example 2 — More Types Than Allowed
$ Input: candyType = [1,1,2,3]
Output: 2
💡 Note: There are 3 unique types (1, 2, 3) but Alice can only eat 4/2 = 2 candies, so maximum variety is 2.
Example 3 — All Same Type
$ Input: candyType = [6,6,6,6]
Output: 1
💡 Note: Only 1 unique type exists. Alice can eat 4/2 = 2 candies, but max variety is limited to 1 type.

Constraints

  • n == candyType.length
  • 2 ≤ n ≤ 104
  • n is even
  • -105 ≤ candyType[i] ≤ 105

Visualization

Tap to expand
Distribute Candies: Maximize Variety Within Constraint112233Input: [1,1,2,2,3,3] (n=6)Unique Types{1, 2, 3} = 3Max Candiesn/2 = 6/2 = 3Constraintmin(3, 3)Alice can eat 3 different typesOne candy each of type 1, 2, and 3
Understanding the Visualization
1
Input
Array of candy types with duplicates
2
Constraints
Can eat n/2 candies, want max variety
3
Output
Maximum different types possible
Key Takeaway
🎯 Key Insight: The answer is always min(unique_types, n/2) - Alice is limited by either variety available or eating constraint
Asked in
Facebook 15 Amazon 10
125.0K Views
Medium Frequency
~15 min Avg. Time
1.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