# Simple Greedy Java Solution

• ``````Arrays.sort(g);
Arrays.sort(s);
int i = 0;
for(int j=0;i<g.length && j<s.length;j++) {
if(g[i]<=s[j]) i++;
}
return i;
``````

Just assign the cookies starting from the child with less greediness to maximize the number of happy children .

[5, 9]
[4, 5, 5]

edited:
sorry I miss this "You cannot assign more than one cookie to one child".

• C++ Version
int findContentChildren(vector<int>& g, vector<int>& s) {
sort(g.begin(),g.end());
sort(s.begin(),s.end());
int m = g.size(), n = s.size(), i=0, j=0;
for(; i<m && j<n; j++){
if(g[i] <= s[j])i++;
}
return i;
}

• one more judge.

``````    Arrays.sort(g);
Arrays.sort(s);
count = s.length-1;
for(int i=g.length-1; i>=0; i--)
if(g[i] <= s[count])	{
re++;
count--;
if(count <0)
break;
}``````

• @fabrizio3 Sorry, but this fails on the test-case:
g: [7,8,9,10]
s: [5,6,7,8]
Since we are comparing the elements in order, the 'g' values 7 and 8 would not be checked against those for 's' leading to an incorrect output of '0' (while the right answer would be '2').

• @abhishek_naik

The solution passes this test-case though...

• @BatCoder But the greedy method works on your test case, both has answer of 2.

• g: [7,8,9,10]
s: [5,6,7,8]

in this case, when j at 0 and 1, i still remains at 0. The loop only increases j but not i.
When j at 2, i will increase to 1 because s[2] = 7 and g[0] = 7.

• @BatCoder since i only moves back one index when gi <= sj, so when g is 7, the s will be 7 and then g 8 will compare with s 8. It will not fail.

• @fabrizio3

Here's a slightly more readable version:

``````public class Solution {
public int findContentChildren(int[] children, int[] cookies) {
Arrays.sort(children);

int child = 0;
child ++;
}
}

return child;
}
}
``````

• @fabrizio3 Good,learn a lot from your solution,thx, :)

• I solved it my way looking oddly similar to this.

My question now is, is calling `arrays.sort` even allowed in interviews?

• @fabrizio3 For the case [1,2,3,4,5,6], [100], the answer should be 1 or 6?

• @linmumu The answer should be 1, because it is said in the note that "You cannot assign more than one cookie to one child".

• @lawonga best is to check with interviewer and ask if they want you to implement a sorting technique. most likely they would say no in which case you should be able to blurt out the efficient sorting techniques you could use eg: Arrays.sort uses quick sort underneath.