구명보트
🔍 알고리즘 분류
💡 문제 풀이
- 몸무게 오름차순 정렬
start, end 인덱스 설정
- 몸무게가 무거운 사람(
end)부터 보트에 태우면서 첫 번째 사람start도 같이 태울 수 있는지 확인
- 같이 태울 수 있다면
start++ (= 첫 번째 사람 태웠다는 의미), 없다면 그대로
end-- (= 마지막 사람 태웠다는 의미) 하며 start <= end 일 때까지 반복
- 보트 1개 사용했으므로
answer++
📄 코드
#include <string>
#include <vector>
#include <algorithm>
using namespace std;
int solution(vector<int> people, int limit) {
int answer = 0;
sort(people.begin(), people.end());
int start = 0;
int end = people.size() - 1;
while (start <= end) {
if (people[start] + people[end] <= limit) start++;
end--;
answer++;
}
return answer;
}