
- C++ Basics
- C++ Home
- C++ Overview
- C++ Environment Setup
- C++ Basic Syntax
- C++ Comments
- C++ Data Types
- C++ Variable Types
- C++ Variable Scope
- C++ Constants/Literals
- C++ Modifier Types
- C++ Storage Classes
- C++ Operators
- C++ Loop Types
- C++ Decision Making
- C++ Functions
- C++ Numbers
- C++ Arrays
- C++ Strings
- C++ Pointers
- C++ References
- C++ Date & Time
- C++ Basic Input/Output
- C++ Data Structures
- C++ Object Oriented
- C++ Classes & Objects
- C++ Inheritance
- C++ Overloading
- C++ Polymorphism
- C++ Abstraction
- C++ Encapsulation
- C++ Interfaces
Distribute Candies in C++
Suppose we have an array with even length, here different numbers in this array will represent different kinds of candies. Now each number means one candy of the corresponding kind. we have to distribute candies equally in number to brother and sister. We have to find the maximum number of kinds of candies the sister could receive.
So, if the input is like [1,1,2,3], then the output will be 2 as if we consider the sister has candies [2,3] and the brother has candies [1,1]. Now the sister has two different kinds of candies, the brother has only one kind of candies.
To solve this, we will follow these steps −
Define one set s
for initialize i := 0, when i < size of candies, update (increase i by 1), do −
insert candies[i] into s
return a minimum of size of s and size of candies / 2
Example
Let us see the following implementation to get a better understanding −
#include <bits/stdc++.h> using namespace std; class Solution { public: int distributeCandies(vector<int>& candies){ unordered_set<int> s; for (int i = 0; i < candies.size(); i++) s.insert(candies[i]); return min(s.size(), candies.size() / 2); } }; main(){ Solution ob; vector<int> v = {1,1,2,3}; cout << (ob.distributeCandies(v)); }
Input
{1,1,2,3}
Output
2
- Related Articles
- Distribute Candies to People in Python
- C++ program to check whether we can distribute bags so that two friends will get same amount of candies
- Program to count the number of ways to distribute n number of candies in k number of bags in Python
- Distribute Coins in Binary Tree in C++
- Maximum Candies You Can Get from Boxes in C++
- Maximum number of candies that can be bought in C
- C++ code to find who cannot give sufficient candies
- Program to distribute repeating integers in Python
- Minimum number of mails required to distribute all the questions using C++.
- If Ramu has 133 chocolates and he has to distribute all chocolates to 120 children, how will he distribute ?
- C++ Program to check given candies can be split with equal weights or not
- Distribute extra horizontal and vertical space in a GridBagLayout with Java
- The 6 Best and 5 Worst Candies for Your Health
- Find the minimum and maximum amount to buy all N candies in Python
- Program to count number of ways we can distribute coins to workers in Python
