์•Œ๊ณ ๋ฆฌ์ฆ˜

ํ”„๋กœ๊ทธ๋ž˜๋จธ์Šค - ๊ตฌ๋ช…๋ณดํŠธ (Greedy)

ghtis1798 2021. 6. 23. 20:58

 

๐Ÿ”ธ ๋ฌธ์ œ ์ ‘๊ทผ ๋ฐฉ์‹

  1. ๊ฐ€์žฅ ๋ฌด๊ฑฐ์šด ์‚ฌ๋žŒ์„ ๋จผ์ € ํƒœ์šด๋‹ค.
  2. ๊ฐ€์žฅ ๊ฐ€๋ฒผ์šด ์‚ฌ๋žŒ๋ถ€ํ„ฐ ๋ณดํŠธ์— ํƒœ์›Œ๋‚˜๊ฐ„๋‹ค.
  3. ๋ณดํŠธ ๋ฌด๊ฒŒ๊ฐ€ limit๋ฅผ ์ดˆ๊ณผํ•˜๋ฉด, ๊ฐ€๋ฒผ์šด ์‚ฌ๋žŒ์„ ํ•œ ๋ช… ๋‚ด๋ฆฌ๊ณ  1๋ฒˆ์œผ๋กœ ๋Œ์•„๊ฐ„๋‹ค.

โ— ์ฃผ์˜ ์‚ฌํ•ญ

์ฒ˜์Œ์— ๋ฆฌ์ŠคํŠธ์˜ ์›์†Œ๊ฐ€ ๋‚จ์•„์žˆ์„ ๋•Œ๊นŒ์ง€ While๋ฌธ์„ ๋ฐ˜๋ณตํ•˜์˜€๋‹ค.

ํ•˜์ง€๋งŒ ๋ฆฌ์ŠคํŠธ ์‚ญ์ œ ์—ฐ์‚ฐ ์ˆ˜ํ–‰ ์‹œ ์‹œ๊ฐ„์ดˆ๊ณผ๊ฐ€ ๋ฐœ์ƒํ–ˆ๋‹ค.

๋ฆฌ์ŠคํŠธ ์›์†Œ ์ตœ๋Œ€๊ฐ’์ด 50,000์ž„์—๋„ ๋น„ํšจ์œจ์ ์ธ ์•Œ๊ณ ๋ฆฌ์ฆ˜์œผ๋กœ ํŒ๋ช…๋˜์—ˆ๋‹ค.

๋”ฐ๋ผ์„œ ๋ฆฌ์ŠคํŠธ๋ฅผ ์‚ญ์ œํ•˜๋Š” ๋Œ€์‹ , left, index ํฌ์ธํ„ฐ๋ฅผ ๋‘๊ณ  indexingํ•˜์˜€๋‹ค.

๐Ÿ’ง Source Code

def solution(people, limit):
    ''' https://programmers.co.kr/learn/courses/30/lessons/42885

    Notes:
        1. ๊ฐ€์žฅ ๋ฌด๊ฑฐ์šด ์‚ฌ๋žŒ์„ ๋จผ์ € ํƒœ์šด ํ›„ ๊ฐ€๋ฒผ์šด ์‚ฌ๋žŒ์„ ํƒœ์›Œ ๋‚˜๊ฐ„๋‹ค.
        2. ๋ฆฌ์ŠคํŠธ ์š”์†Œ๋ฅผ ์‚ญ์ œ ํ•˜๋Š” ์—ฐ์‚ฐ ๋Œ€์‹  indexing์œผ๋กœ ๋Œ€์ฒดํ•œ๋‹ค.

    Args:
        people (list): ๊ตฌ์กฐํ•  ์‚ฌ๋žŒ์˜ ์ฒด์ค‘(int)๋“ค์ด ๋‹ด๊ธด ๋ฆฌ์ŠคํŠธ
        limit (int): ๊ตฌ๋ช…๋ณดํŠธ์˜ ์ตœ๋Œ€ ๋ฌด๊ฒŒ

    Returns:
        cnt (int): ํ•„์š”ํ•œ ์ตœ์†Œ ๊ตฌ๋ช…๋ณดํŠธ ์ˆ˜
    '''

    people.sort(reverse=True)
    cnt = 0

    left, right = 0, len(people)-1

    while left <= right:
        boat = people[left]
        cnt += 1
        left += 1

        while boat <= limit:
            if left > right:
                return cnt
            small = people[right]
            boat += small
            right -= 1
        right += 1

    return cnt

def worst_solution(people, limit):
    people.sort(reverse=True)
    cnt = 0

    while people:
        boat = people.pop(0)
        cnt += 1

        while boat <= limit:
            if len(people) == 0:
                return cnt
            small = people.pop()
            boat += small
        people.append(small)
    return cnt