문제풀이/일일연습문제

[Greedy]99클럽 코테 스터디 37일차 TIL + 0455-assign-cookies

Mo_bi!e 2024. 8. 30. 13:05

455. Assign Cookies

Easy


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.

 

Constraints:

  • 1 <= g.length <= 3 * 104
  • 0 <= s.length <= 3 * 104
  • 1 <= g[i], s[j] <= 231 - 1

 

Note: This question is the same as 2410: Maximum Matching of Players With Trainers.

 

 

<내 코드>

* 첫번째 코드

class Solution:
    def findContentChildren(self, g: List[int], s: List[int]) -> int:
        for cookie in s :
            if g is None : return output
            for kid in g:
                if cookie >= kid :
                    print(cookie)
                    print(kid)
                    output += 1
                    g = g[1:]
                    continue
        return output

- 처음에는 이중 반복문으로 직렬식으로 생각했음.

=> 하지만 이렇게 하면 cookie 가 kid 에게 전달이 되더라도 kid 관련 반복문은 반복되면서 여러번 주게되는 문제가 발생함!

이러한 문제를 해결하기 위해서 병렬식으로 인덱스를 높여주여야함

 

- 탐욕적인 접근은 정렬부터 시작한

 

 

* 두번째 코드

class Solution:
    def findContentChildren(self, g: List[int], s: List[int]) -> int:
        g.sort() # kid
        s.sort() # cookie
        print(s)
        print(g)
        output = 0
        g_index = 0
        s_index = 0

        while g_index < len(g) and s_index < len(s):
            if s[s_index] >= g[g_index] :
                print(s_index)
                print(g_index)
                s_index += 1
                g_index += 1
                output += 1
            else :
                s_index += 1
        return output

- for 문은 하나씩 꺼내주는 logic 이 있음 이 경우 zip() 으로도 병렬가능하다.

=> 하지만 g_index는 특정 조건에서만 증가 연산을 해야하기 때문에 부적절하다.

=> 결국에 while 로 별도로 index 관래해주는것이 바람직함

 

- 이 방식은 합병정렬 , 퀵정렬 부분과 느낌이 비슷함 즉 분할정복 느낌같음

합병정렬은 병합단계 / 퀵정렬은 분할단계 에서 조건에 따라 인덱스 증가하는 방식임

 

 

<모범사례>

class Solution:
    def findContentChildren(self, g, s):
        # Sort the arrays
        g.sort()
        s.sort()
        
        # Initialize count for tracking assignments of cookies
        count = 0
        # Initialize two pointers i and j to iterate on g and s
        i, j = 0, 0
        
        # Iterate through the arrays
        while i < len(g) and j < len(s):
            # If the size of the cookie is greater than or equal to the child's greed,
            # assign the cookie to the child and move both pointers
            if g[i] <= s[j]:
                count += 1
                i += 1
            # Move the cookie pointer to the next cookie, regardless of assignment
            j += 1
        
        return count

 

j+= 1 은 조건에 관계없이 늘 증가연산하기 때문에 조건문 밖으로 하는것이 좋음