[C++] 프로그래머스 : 구명보트

wldud·2024년 6월 16일
0

알고리즘

목록 보기
16/34
#include <string>
#include <vector>
#include <algorithm>

using namespace std;

int solution(vector<int> people, int limit) {
    int answer = 0;
    //무게를 내림차순으로 정렬
    sort(people.begin(), people.end(),greater<int>());
    
    int start = 0;
    int end = people.size() - 1;
    while(start <= end){
        int sum = 0;
        sum += people[start];
        if(sum + people[end] <= limit){
            end--;
        }
        answer++;
        start++;
    }
    
    return answer;
}

가장 무거운 사람과 가장 가벼운 사람을 더해서 limit값보다 작으면 같이 구명보트에 타고 아니면 무거운 사람만 타도록 코드를 작성하였다.

아이디어는 빨리 생각해냈는데 문제에서 구명보트는 작아서 한 번에 최대 2명씩 밖에 탈 수 없고 를 제대로 못봐서 시간이 좀 걸렸다.. 다음부터는 문제 좀 열심히 봐야지..

0개의 댓글