algoadvance

Leetcode 575. Distribute Candies

Problem Statement

Leetcode Problem 575: Distribute Candies

Alice has n candies, where the candies are represented by an integer array candyType of length n. Each candy is of a different type, indicated by different integers. Alice wants to eat n / 2 candies, but she also wants to eat as many different types of candies as possible. Return the maximum number of different types of candies she can eat if she only eats n / 2 candies.

Clarifying Questions

  1. Input Constraints:
    • Is it guaranteed that the length of the array n is always even?
    • Are there any constraints on the range of values for candyType?
  2. Output:
    • Can Alice eat fewer than n / 2 candies if it allows her to eat more types?

Example

Let’s assume:

Explanation:

Strategy

  1. Understanding Different Strategy:
    • First, count the number of unique candy types.
    • Alice can eat n / 2 candies but she also wants to maximize the number of different types.
    • The result will be the minimum between the unique candy types and n / 2 because she can’t eat more types than candies allowed.
  2. Algorithm:
    • Calculate n / 2 where n is the length of candyType.
    • Use a set to find the unique types of candies.
    • Compare the size of the set with n / 2 and return the smaller number.
  3. Efficient Implementation:
    • Using a set provides average O(1) time complexity for insertions and lookups, which will help us quickly count unique types.
    • Space complexity is O(k) where k is the number of unique types.

Time Complexity

Code

#include <vector>
#include <unordered_set>
using namespace std;

class Solution {
public:
    int distributeCandies(vector<int>& candyType) {
        unordered_set<int> uniqueCandies(candyType.begin(), candyType.end());
        int maxCandiesAliceCanEat = candyType.size() / 2;
        
        // The maximum number of different types Alice can eat
        return min(maxCandiesAliceCanEat, (int)uniqueCandies.size());
    }
};

Explanation of the Code:

  1. Initialization:
    • Calculate n / 2 which represents the maximum number of candies Alice can eat.
  2. Use of Unordered Set:
    • By inserting the elements of candyType into an unordered set, we automatically filter out duplicates and get the count of unique candy types.
  3. Return the Result:
    • The answer is the minimum value between the number of unique candy types and n / 2.

This approach ensures that we maximize the number of different types of candies Alice can eat while adhering to the constraint of eating no more than n / 2 candies.

Cut your prep time in half and DOMINATE your interview with AlgoAdvance AI