Each child
i
has a greed factor g[i]
, which is the minimum size of a cookie that the child will be content with; and each cookie j
has a size s[j]
. If s[j] >= g[i]
, we can assign the cookie j
to the child i
, and the child i
will be content. Your goal is to maximize the number of your content children and output the maximum number.Example:
Input: g[]={1,2,3},s={1,1}
Output: 1
Approach
Java
import java.util.Arrays;public class AssignCookies {public static void main(String[] args) {int g[] = { 1, 2, 3 };int s[] = { 1, 1 };System.out.println(findContentChildren(g, s));}private static int findContentChildren(int[] g, int[] s) {// sort both the arraysArrays.sort(g);Arrays.sort(s);int n = g.length;int m = s.length;int i = 0, k = 0, cnt = 0;while (k < m) {if (s[k] >= g[i]) {cnt++;k++;i++;if (i == n)break;} elsek++;}return cnt;}}
C++
#include <bits/stdc++.h>using namespace std;int findContentChildren(vector<int>& g,vector<int>& s) {//sort both the arrayssort(g.begin(),g.end());sort(s.begin(),s.end());int n=g.size(),m=s.size();int i=0,k=0,cnt=0;while(k<m){if(s[k]>=g[i]){cnt++;k++;i++;if(i==n)break;}elsek++;}return cnt;}int main(){vector<int>g = {1,2,3}, s ={1,1};cout<<findContentChildren(g,s);return 0;}
No comments:
Post a Comment