Assume you are an awesome parent and want to give your children some cookies. But, you should give each child at most one cookie.
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 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.
And even though you have 2 cookies, since their size is both 1, you could only make the child whose greed factor is 1 content.
You need to output 1.
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.
You have 3 cookies and their sizes are big enough to gratify all of the children,
You need to output 2.
해답
function findContentChildren(g: number[], s: number[]): number {
if (g.length < 1 || s.length < 1) return 0;
g = g.sort((a, b) => a - b);
s = s.sort((a, b) => a - b);
let child = 0;
let cookieIndex = 0;
while (cookieIndex < s.length && child < g.length) {
if (s[cookieIndex] >= g[child]) {
child++;
cookieIndex++;
} else {
cookieIndex++;
}
}
return child;
}
g = g.sort((a, b) => a - b);
- 오름 차순 정렬
- 만약 (a, b) => b - a 면 내림차순
Ex) 아이들의 욕구 배열 g: [1, 2]. 쿠키 크기 배열 s: [1, 2, 3]
- cookieIndex < s.length (0 < 3)와 child < g.length (0 < 2)를 확인. 둘 다 참이므로 반복문을 실행.
첫 번째 반복:
- s[cookieIndex] (1) >= g[child] (1): 쿠키가 아이의 욕구를 만족
- child++ (1로 증가)
- cookieIndex++ (1로 증가)
두 번째 반복:
- cookieIndex < s.length (1 < 3)와 child < g.length (1 < 2)를 확인. 둘 다 참이므로 반복문을 실행
- s[cookieIndex] (2) >= g[child] (2): 쿠키가 아이의 욕구를 만족
- child++ (2로 증가)
- cookieIndex++ (2로 증가)
세 번째 반복:
- cookieIndex < s.length (2 < 3)와 child < g.length (2 < 2)를 확인. 둘 중 하나가 거짓이므로 반복문을 종료
'LeetCode' 카테고리의 다른 글
| 2932. Maximum Strong Pair XOR I / TypeScript (0) | 2024.05.19 |
|---|---|
| 2562. Find the Array Concatenation Value / TypeScript (0) | 2024.05.18 |
| 1695. Maximum Erasure Value / TypeScript (0) | 2024.05.17 |
| 2427. Number of Common Factors (0) | 2024.05.15 |
| 1143. Longest Common Subsequence (TypeScript) (0) | 2024.05.15 |