Cookies distribution

(Programming) biscuit distribution Suppose you are a parent, you want to give your kids some cookies, you can give a child up to a biscuit. Each child i have a greed factor gi, gi means that you can meet this the minimum size of a child i of biscuits. each biscuit j have their own size sj, if sj ≥ gi, we can assign cookies to the children j i, i child will be met. The goal is to maximize the number of satisfied children and outputs to meet the number of children.

Example 1:

Input: The first line greed factor, the size of the second row of biscuits

1 2 3

1 1

Output:

1

Example 2:

Input: 1 2 

1 2 3

Output:

2

 

Ideas: want to go up to meet the child's appetite, our strategy is to take on the greed factor and biscuit size sorting. Then start from the smallest child appetite, to satisfy the appetite of his minimum biscuits. Providing two pointers, one for the greedy, one for the cookie size.

public int find(int[] greedy ,int[] cookies) {

      Arrays.sort(greedy);

      Arrays.sort(cookies);

      int ret = 0;

      for(int i = 0 , j = 0;i <greedy.length && j < cookies.length;) {

          if(greedy[i] <= cookies[j]) {

             i++;

             j++;

             entitled ++;

          }else {

             j++;

          }

      }

      return ret; 

   }

Guess you like

Origin blog.csdn.net/weixin_43821874/article/details/94737387