Assign Cookies

Problem

The first array has the greed of each child (the smallest cookie size the child accepts). The second array has the sizes of the cookies. Each child gets at most one cookie, and each cookie goes to at most one child. A child is happy if the cookie size is at least the child's greed. Print the largest number of happy children.

Constraints

  • 1 <= n, m <= 10^5

Examples

Input

3
1 2 3
2
1 1

Output

1

Solutions

Best approachTime O(n log n + m log m)Space O(n + m)

Greedy matching: the smallest cookie that is big enough should go to the least greedy child. Sorting makes this a simple two-pointer scan.

Same code works in Java810172125Basic features only, so nothing changes between versions.
/*
 * Problem : Count happy children.
 * Input   : Two arrays.
 * Output  : The number of happy children.
 * Approach: Sort and match.
 * Time    : O(n log n + m log m)
 * Space   : O(n + m)
 * Java    : 8 or newer.
 */
import java.util.Scanner;

public class Main {
    // This method solves the task. It receives the input and returns the answer.
    static int solve(int[] a, int[] b) {
        // Step 1: Sort both arrays. Then we can match the smallest greed with the smallest cookie that is big enough.
        int[] greed = a.clone();
        int[] cookies = b.clone();
        java.util.Arrays.sort(greed);
        java.util.Arrays.sort(cookies);

        // Step 2: child = the next child that needs a cookie.
        int child = 0;

        // Step 3: Offer each cookie, from small to big, to the least greedy child who is still sad.
        for (int cookie : cookies) {
            if (child < greed.length && greed[child] <= cookie) {
                child++;
            }
        }
        return child;
    }

    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);
        int size = scanner.nextInt();
        int[] a = new int[size];
        for (int i = 0; i < size; i++) {
            a[i] = scanner.nextInt();
        }
        int sizeB = scanner.nextInt();
        int[] b = new int[sizeB];
        for (int i = 0; i < sizeB; i++) {
            b[i] = scanner.nextInt();
        }
        System.out.println(solve(a, b));
    }
}
Hints (1)
  1. Why sort both arrays?