본문 바로가기
코딩 테스트/프로그래머스

구명보트

by ornni 2024. 6. 15.
728x90
반응형

첫번째 코드

 

순서대로 정렬한 후에

index1 = 처음부터 시작하는 index

index2 = 마지막부터 시작하는 index

그렇게 index1의 값과 index2의 값을 더해 limit보다 크면 index1은 그대로 누고 index2 -= 1이면서 answer += 1

index1의 값과 index2의 값을 더해 limit보다 작으면 index1 += 1, index2 -= 1를 적용한다.

 

이는 최대 2명까지만 보트에 탑승이 가능하기 때문에 가능한 것이다.

 

def solution(people, limit):
    answer = 0
    
    people.sort()
    index1 = 0
    index2 = len(people) - 1
    
    while index1 <= index2:
        if index1 == index2:
            answer += 1
            break
        if people[index1] + people[index2] <= limit:
            index1 += 1
        index2 -= 1
        answer += 1
    
    return answer

 

통과!


링크

https://github.com/ornni/programmers/tree/main/%ED%94%84%EB%A1%9C%EA%B7%B8%EB%9E%98%EB%A8%B8%EC%8A%A4/2/42885.%E2%80%85%EA%B5%AC%EB%AA%85%EB%B3%B4%ED%8A%B8

 

programmers/프로그래머스/2/42885. 구명보트 at main · ornni/programmers

repository for recording Programmers Algorithm problem solving - ornni/programmers

github.com

 

반응형

'코딩 테스트 > 프로그래머스' 카테고리의 다른 글

서울에서 김서방 찾기  (2) 2024.07.01
수박수박수박수박수박수?  (0) 2024.06.30
두 정수 사이의 합  (0) 2024.06.12
문자열 다루기 기본  (0) 2024.06.10
행렬 테두리 회전하기  (0) 2024.06.09