본문 바로가기
이론/코딩테스트

[프로그래머스] level2 구명보트 (그리디 + 투포인터)

by 퇴근후개발 2022. 8. 29.
반응형

-문제

 

 

-코드

#include <string>
#include <vector>
#include <algorithm>

using namespace std;

int solution(vector<int> people, int limit) {
    int answer = 0,  p1=0, p2=people.size()-1;
    
    sort(people.begin(), people.end());

    while(p1<= p2)
    {
        if (p1== p2)
        {
            answer++;
            break;
        }
        if(people[p1] + people[p2] <= limit )
        {
            answer++;
            p1++;
            p2--;
        }
        else
        {
            answer++;
            p2--;
        }
    }
    return answer;
}
반응형