프로그래머스 Lv.2 코딩테스트

[프로그래머스 Lv.2] 구명보트

하다블 2023. 2. 22. 18:02
반응형

문제는 다음과 같습니다.

https://school.programmers.co.kr/learn/courses/30/lessons/42885

 

프로그래머스

코드 중심의 개발자 채용. 스택 기반의 포지션 매칭. 프로그래머스의 개발자 맞춤형 프로필을 등록하고, 나와 기술 궁합이 잘 맞는 기업들을 매칭 받으세요.

programmers.co.kr

 

풀이 코드는 다음과 같습니다.

#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 idx{0};
    while(idx<people.size())
    {
        int back = people.back();
        people.pop_back();
        if(people[idx]+back<=limit)
        {
            answer++;
            idx++;
        }
        else
        {
            answer++;
        }
    }
    return answer;
}

무게를 오름차순으로 정리한 다음, 맨 뒤의 사람을 무조건 빼냅니다.

거기에서 가장 가벼운 사람이 무게제한에 걸리지 않는다면 같이 빼냅니다. (while문에 있는 if문)

이 과정을 반복해서 최소 횟수로 움직일 수 있습니다.

 

반응형