clueless coding // TODO: be smarter

LeetCode Assign Cookies: Java Solution



Problem Statement


Assume that you are handing out cookies to children.

Assume also that you should give each child at most one cookie.

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.

If sj >= gi, we can assign the cookie j to the child i, and the child i will be content.

Maximize the number of your content children and output the maximum number.

Function Signature (Java):
  int findContentChildren(int[] g, int[] s)

Inputs:
  g = [1,2,3]
  s = [1,1]

Outputs:
  1

You have 3 children and 2 cookies.

You can give one cookie to the child with greed factor 1, and he/she will be satisfied.

However, the next cookie is too small; we only have a cookie of size one, and both children left would only be satisfied with size 2 and 3 cookies.

Therefore, we can satisfy only one child.



TL;DR Code Solution


public int findContentChildren(int[] g, int[] s) {

    Arrays.sort(g);
    Arrays.sort(s);

    int gp = 0;
    int sp = 0;

    while (gp < g.length && sp < s.length) {
        if (s[sp] >= g[gp]) {
            gp++;
        }
        sp++;
    }

    return gp;

}