Array sort + Two pointer greedy solution O(nlogn)


  • 10
    A

    Two assign cookies to children optimaly we should give for each child the closest higher cookie. By using this greedy approach overall sum of wasted cookies will be minimum amoung all. To use this greedy solution in effective way we can sort both arrays and use two pointers. We should move pointer of children only if there is enough cookies to make that child content. In each step we will try to make content child at position pointerG by searching the closes higher cookie value.

    public class Solution {
        public int findContentChildren(int[] g, int[] s) {
            Arrays.sort(g);
            Arrays.sort(s);
            
            int pointG = 0;
            int pointS = 0;
            
            while (pointG<g.length && pointS<s.length) {
                if (g[pointG]<=s[pointS]) {
                    pointG++;
                    pointS++;
                } else {
                    pointS++;
                }
            }
            
            return pointG;
        }
    }
    

  • 1
    P

    @amanchik you are right! To be more precise, it is obvious that we should start from child who has a lowest greed factor g_i. If we cannot find to him a satisfying cookie then we cannot find to any other child. And it is clear that the best suitable cookie will be the first cookie which's s_j >= g_i. Moreover, we can skip considering all the s_k such that s_k <= s_j, because the next child will come with a higher g_i.


  • 0
    Y

    Why is it O(n logn)?


  • 0
    A

    @yttuo Because we are sorting the arrays at the beginning


  • 0
    K

    @amanchik you just go through the array s, isnt it O(n)?


  • 0
    A

    @kawayee No, the time complexity of the function is O(2nlogn) + O(n), so after all it is O(nlogn)


  • 0
    H

    Hi I do not think it is O(nlgn) cause the best case of Arrays.sort(g) is O(nlgn) while the worst case is O(n^n).


  • 0

    same idea

    public class Solution {
        public int findContentChildren(int[] g, int[] s) {
            int count = 0;
            int index1 = 0;
            int index2 = 0;
            Arrays.sort(g);
            Arrays.sort(s);
            while (index1 < g.length && index2 < s.length) {
                if (s[index2] >= g[index1]) {
                    count++;
                    index1++;
                }
                index2++;
            }
            return count;
        }
    }
    

Log in to reply
 

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