0575. Distribute Candies

575. Distribute Candies #

Problem #

Given an integer array with even length, where different numbers in this array represent different kinds of candies. Each number means one candy of the corresponding kind. You need to distribute these candies equally in number to brother and sister. Return the maximum number of kinds of candies the sister could gain.

Example 1:

Input: candies = [1,1,2,2,3,3]
Output: 3
Explanation:
There are three different kinds of candies (1, 2 and 3), and two candies for each kind.
Optimal distribution: The sister has candies [1,2,3] and the brother has candies [1,2,3], too. 
The sister has three different kinds of candies.

Example 2:

Input: candies = [1,1,2,3]
Output: 2
Explanation: For example, the sister has candies [2,3] and the brother has candies [1,1]. 
The sister has two different kinds of candies, the brother has only one kind of candies.

Note:

  1. The length of the given array is in range [2, 10,000], and will be even.
  2. The number in given array is in range [-100,000, 100,000].

Problem Summary #

Given an array of even length, where different numbers represent different kinds of candies, and each number represents one candy. You need to distribute these candies equally between a brother and a sister. Return the maximum number of different kinds of candies the sister can get.

Solution Approach #

  • Given a candies array, each element represents the kind of candy, and the same number represents the same kind. Distribute these candies to the brother and sister, and ask how many kinds of candies the sister can get at most. This problem is relatively simple. Use a map to count the occurrence frequency of each candy. If the total number of kinds is less than n/2, then return len(map); otherwise, return n/2 (that is, give half of them to the sister).

Code #


package leetcode

func distributeCandies(candies []int) int {
	n, m := len(candies), make(map[int]struct{}, len(candies))
	for _, candy := range candies {
		m[candy] = struct{}{}
	}
	res := len(m)
	if n/2 < res {
		return n / 2
	}
	return res
}


Calendar Jun 25, 2026
Edit Edit this page
Total visits:   You are visitor No.
中文