C# - use as many cookies as possible


  • 0

    The problem says make as many children content as possible but because we can only use 1 cookie per child the problem is equally stated as use as many cookies as possible.

    To solve this use you could either start using cookies from the smallest and working upward or the largest and working downward. Here I start with the largest cookie (not that is matters, but this way gives the greatest total quantity of contentedness!).

    Sort both the cookies and children arrays, start with pointers to both of the large ends of the arrays and as soon as a cookie is large enough for the child give them that cookie. If the cookie is too small then that child will have to be skipped.

        public int FindContentChildren(int[] g, int[] s) 
        {
            int count = 0;
            int child = g.Length - 1;
            int cookie = s.Length - 1;
            
            Array.Sort(g);
            Array.Sort(s);
            
            while (child >= 0 && cookie >= 0)
            {
                if (g[child] <= s[cookie])
                {
                    count++;
                    cookie--;
                }
                child--;
            }
            return count;
        }
    

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.