[programmers] 구명보트

KwonSC·2022년 5월 20일
0

programmers - Python

목록 보기
20/23
post-thumbnail

https://programmers.co.kr/learn/courses/30/lessons/42885


Code

from collections import deque

def solution(people, limit):
    people.sort()
    people = deque(people)
    answer = 0
    while (people):
        first = people.popleft()
        i = len(people) - 1
        while (people and i >= 0 and people[i] + first > limit):
            i -= 1
            people.pop()
            answer += 1
        if (i >= 0 and people[i] + first <= limit):
            people.pop()
        answer += 1
    return answer

Solution

people을 정렬후 deque에 넣고 시작을 한다. while문을 도는데 first는 현재 가장 몸무게가 덜 나가는 인원이고 맨 끝에서 부터 역순으로 first와 같이 탈수있는 인원을 찾는데 못타는 인원은 혼자서 밖에 탈수 없으니(first보다 몸무게가 덜 나가는 인원은 없음) pop시키면서 answer를 증가시킨다. while문을 돌고나서 if문으로 first와 탈수 있는 인원인지 체크를 하고 Truepop시킨후 answer를 증가시킨다. 이 while문을 돌고나서 answer를 리턴하면 끝.

0개의 댓글