Leetcode 575. Distribute Candies
Given an integer array candyType representing the types of candies (where each type is represented by a unique integer), you need to determine the maximum number of different types of candies that can be eaten if you can only eat n / 2 candies (where n is the total number of candies).
In other words, you need to distribute the candies in such a way that maximizes the number of unique candy types eaten, provided that you can only eat half of the total candies.
candyType array?candyType?import java.util.HashSet;
public class Solution {
public int distributeCandies(int[] candyType) {
// Calculate the maximum number of candies that the sister can eat
int maxCandies = candyType.length / 2;
// Use a HashSet to store the unique types of candies
HashSet<Integer> uniqueCandies = new HashSet<>();
// Add each candy type to the HashSet
for (int type : candyType) {
uniqueCandies.add(type);
}
// The sister can either eat all unique candy types or maxCandies, whichever is smaller
return Math.min(uniqueCandies.size(), maxCandies);
}
}
HashSet to store all unique candy types.candyType array and add each type to the HashSet.HashSet (unique types) and the previously calculated maxCandies.O(n), where n is the number of elements in the candyType array. This is because we are iterating through the array once.O(n), for storing up to n unique candy types in the HashSet.This approach ensures that the solution is both time and space efficient given the constraints of typical interview problems.
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?