-
프로그래머스 - 구명보트Algorithm 2023. 6. 7. 18:16
문제
풀이
사람들을 담은 배열 people을 몸무게가 가벼운 순인 오름차순으로 정렬시킨다
보트에 people 배열에서 가장 무거운 사람을 태운 뒤, people 배열에서 가장 가벼운 사람을 태울 수 있는지 확인한다
두 사람이 탈 수 있다면 두 사람을 태워 보내고 불가능하다면 다음으로 무거운 사람을 태운 뒤 확인한다
이 과정을 people 배열에 아무도 남지 않을 때 까지 반복한다
function solution(people, limit) { let answer = 0; let boat = []; people.sort((a, b) => a - b); while(people.length) { boat.push(people.pop()); // 보트에 탄 사람의 무게 + 가장 가벼운사람의 무게가 limit보다 크지 않다면 if(boat[0] + people[0] <= limit) { // 둘 다 탑승 boat.push(people.shift()); answer++; boat = []; } // 아니라면 else { // 다음 보트 answer++; boat = []; } } return answer; }
'Algorithm' 카테고리의 다른 글
프로그래머스 데브코스 - [3단계] 가장 먼 노드 (0) 2023.06.12 프로그래머스 - 하노이 탑 (0) 2023.06.07 프로그래머스 - 게임 맵 최단거리 (0) 2023.05.30 프로그래머스 - 바탕화면 정리 (0) 2023.05.26 프로그래머스 - 폰켓몬 (0) 2023.05.25