Solution 1 - Use a Set
Answer is min(#unique_types, n/2).
TimeComplexity:O(n) SpaceComplexity:O(n) """ 0575.1 - Distribute Candies - Solution 1 - Use a Set """
from typing import List
class Solution:
def distributeCandies(self, candyType: List[int]) -> int:
return min(len(set(candyType)), len(candyType) // 2)
if __name__ == "__main__":
print(Solution().distributeCandies([1,1,2,2,3,3])) # 3
function distributeCandies(candyType){
return Math.min(new Set(candyType).size, candyType.length/2);
}
function distributeCandies(candyType:number[]):number{
return Math.min(new Set(candyType).size, candyType.length/2);
}
package main
func distributeCandies(candyType []int) int {
m := map[int]bool{}
for _, x := range candyType {
m[x] = true
}
half := len(candyType) / 2
if len(m) < half {
return len(m)
}
return half
}
func main() {}
use std::collections::HashSet;
fn distribute_candies(candy_type: &[i32]) -> usize {
let set: HashSet<i32> = candy_type.iter().copied().collect();
set.len().min(candy_type.len() / 2)
}
fn main() {}