455. Distributing cookies (Difficulty: Easy)
Let’s say you’re a great parent and you want to give your kids some cookies. However, no more than one cookie can be given to each child.
For each child I, there is an appetite value g[I], which is the minimum size of a cookie to satisfy a child’s appetite; And every cookie J has a size S [J]. If s[j] >= g[I], we can assign this cookie J to child I, and the child will be satisfied. Your goal is to satisfy as many children as possible and output this maximum number.
Their thinking
In order to satisfy children with low satiety and prioritize the consumption of cookies, the children’s satiety and the size of cookies will be ranked first and then calculated.
Answer key
public int findContentChildren(int[] children, int[] cookies) {
Arrays.sort(children);
Arrays.sort(cookies);
int child = 0;
int cookie = 0;
while(child < children.length && cookie < cookies.length) {
if(children[child] <= cookies[cookie]) {
++child;
}
++cookie;
}
return child;
}
Copy the code
test
AssignCookies assignCookies = new AssignCookies();
private void test_findContentChildren(int[] children, int[] cookies, int expected) {
int childCount = assignCookies.findContentChildren(children, cookies);
Assertions.assertEquals(expected, childCount);
}
@Test
public void text_case1(a) {
test_findContentChildren(new int[] {1.2.3}, new int[] {1.1}, 1);
}
@Test
public void test_case2(a) {
test_findContentChildren(new int[] {1.2}, new int[] {1.2.3}, 2);
}
Copy the code