- Data Structure
- Networking
- RDBMS
- Operating System
- Java
- MS Excel
- iOS
- HTML
- CSS
- Android
- Python
- C Programming
- C++
- C#
- MongoDB
- MySQL
- Javascript
- PHP
- Physics
- Chemistry
- Biology
- Mathematics
- English
- Economics
- Psychology
- Social Studies
- Fashion Studies
- Legal Studies
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Assign Cookies in C++
Suppose we are trying to distribute some cookies to children. But, we should give each child at most one cookie. Now each child i has a greed factor gi, which is the minimum size of a cookie that the child will be content with; and each cookie j has a size sj. When sj >= gi, we can assign the cookie j to the child i, and the child i will be content. Our goal is to maximize the number of content children and output the maximum number.
So, if the input is like [1,2], [1,2,3], then the output will be 2, there are 2 children and 3 cookies. The greed factors of 2 children are 1, 2. Now we have 3 cookies and their sizes are big enough to gratify all of the children, so the output is 2.
To solve this, we will follow these steps −
sort the array g
sort the array s
i := 0, j = 0
while (i < size of g and j < size of s), do −
if g[i] <= s[j], then −
(increase i by 1)
(increase j by 1)
return i
Example
Let us see the following implementation to get a better understanding −
#include <bits/stdc++.h> using namespace std; class Solution { public: int findContentChildren(vector<int>& g, vector<int>& s) { sort(g.begin(), g.end()); sort(s.begin(), s.end()); int i = 0, j = 0; while (i < g.size() && j < s.size()) { if (g[i] <= s[j]) i++; j++; } return i; } }; main(){ Solution ob; vector<int> v = {1,2}, v1 = {1,2,3}; cout << (ob.findContentChildren(v, v1)); }
Input
{1,2}, {1,2,3}
Output
2