0/1 Knapsack
DP on Subsequences DSA practice problem on Onlearn.
Difficulty: hard.
Topics: Binary Search Algorithm, Greedy Algorithm, Sorting, Two Pointers, iteration, array, divide and conquer, search space optimization, pointer operations, recursion, time complexity analysis.
You are given two integer arrays, g and s. The array g represents the greed factors of children, where g[i] is the minimum size cookie that child i will accept. The array s represents the sizes of cookies, where s[j] is the size of the j th cookie. Your goal is to assign cookies to children in a way that maximizes the number of satisfied children. Each child can be assigned at most one cookie, and each cookie can be used at most once. A child i can be satisfied if you assign them a cookie j such that s[j] = g[i]. Return the maximum number of satisfied children. Input: Two integer arrays, g and s. Output: An integer representing the maximum number of satisfied children. Constraints: 1 <= g.length, s.length <= 3 10^4 1 <= g[i], s[j] <= 10^9 Example 1: Input: g = [1,2,3], s = [1,1] Output: 1 Explanation: You have 3 children and 2 cookies. The greed factors of 3 children are 1, 2, 3. The sizes of the 2 cookies are 1, 1. You can only satisfy at most 1 child. Assign cookie 0 to child 0. The greed factor of child 0 is 1, and the cookie size is 1. Since 1 = 1, child 0 is satisfied. Example 2: Input: g = [1,2], s = [1,2,3] Output: 2 Explanation: You have 2 children and 3 cookies. The greed factors of 2 children are 1, 2. The sizes of the 3 cookies are 1, 2, 3. You can satisfy all 2 children. Assign cookie 0 to child 0. The greed factor of child 0 is 1, and the cookie size is 1. Since 1 = 1, child 0 is satisfied. Assign cookie 1 to child 1. The greed factor of child 1 is 2, and the cookie size is 2. Since 2 = 2, child 1 is satisfied.