#575

Distribute Candies

Easy
ArrayHash TableHash MapArray
LeetCode ↗

Approaches

Brute ForceOptimal
Complexity Comparison
Brute ForceOptimal Solution
Time
O(n²)
O(n)
Space
O(1)
O(n)
💡

Intuition

Time O(n)Space O(n)

The optimal solution leverages the properties of sets to count unique candy types directly, avoiding the need for combinations. This is efficient and straightforward.

⚙️

Algorithm

3 steps
  1. 1Step 1: Create a set from the candyType array to get unique candy types.
  2. 2Step 2: Calculate the maximum number of candies Alice can eat, which is n / 2.
  3. 3Step 3: Return the minimum of the size of the unique types set and n / 2.
solution.py3 lines
1def maxUniqueCandies(candyType):
2    unique_types = set(candyType)
3    return min(len(unique_types), len(candyType) // 2)

Complexity note: This complexity is linear because we traverse the candyType array once to create the set of unique types, and the space complexity is also linear due to storing the unique types.

  • 1To maximize unique types, focus on the number of distinct candies available.
  • 2The limit of unique types Alice can eat is constrained by both the number of unique candies and n / 2.

Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.