Leetcode 575. Distribute Candies
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.
n is always even?candyType?n / 2 candies if it allows her to eat more types?Let’s assume:
candyType = [1,1,2,2,3,3]3Explanation:
n / 2 = 6 / 2 = 3 candies.n / 2 candies but she also wants to maximize the number of different types.n / 2 because she can’t eat more types than candies allowed.n / 2 where n is the length of candyType.n / 2 and return the smaller number.#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());
}
};
n / 2 which represents the maximum number of candies Alice can eat.candyType into an unordered set, we automatically filter out duplicates and get the count of unique candy types.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.
Got blindsided by a question you didn’t expect?
Spend too much time studying?
Or simply don’t have the time to go over all 3000 questions?