C++ solution with explaination


  • 0
    D

    We use a unordered_set to store how many kinds of candies.
    If the kind of canids is greater or equal half of candies size. return half of candies size.
    Otherwise, return kinds of candies.

    class Solution {
    public:
        int distributeCandies(vector<int>& candies) {
            unordered_set<int> candy_kinds(candies.begin(), candies.end());
            return candy_kinds.size() >= (candies.size() / 2) ? candies.size() / 2 : candy_kinds.size();
        }
    };
    

  • 0
    H

    @Dongwei.Wang
    Hi
    Thank you for solutions
    Can you explain detail why return haft of candies size when kinds of candies is greater or equal haft of candies size otherwise return kinds of candies ?


  • 0
    D

    @hiepdangnguyendai
    we need divide these candies equally to brother and sister. It also mentions that the length of the vector is a even number.


Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.