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 - Hash Approach INPUT candyType array (n=6) 1 1 2 2 3 3 Input Array: [1, 1, 2, 2, 3, 3] n = 6, can eat n/2 = 3 ALGORITHM STEPS 1 Create HashSet Store unique candy types 2 Add all candies Duplicates auto-removed HashSet Contents 1 2 3 uniqueTypes = 3 3 Calculate limit maxAllowed = n/2 = 3 4 Return minimum min(unique, maxAllowed) min(3, 3) = 3 uniqueTypes vs maxAllowed FINAL RESULT Alice can eat 3 different types: 1 2 3 OK Output 3 Maximum different types Alice can eat = 3 (following doctor's advice) Key Insight: Using a HashSet automatically eliminates duplicate candy types. The answer is simply the minimum of: (1) Number of unique types in the set, and (2) Maximum candies allowed (n/2). Time: O(n) | Space: O(n) for HashSet storage TutorialsPoint - Distribute Candies | Hash Approach
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