[프로그래머스] 구명보트 [cpp]

lsh235·2024년 12월 2일
0

CodingTest

목록 보기
17/31

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

핵심

sort후에 무거운 사람과 가벼운 사람이 같이 탈 수 있는지 확인.
같이 탈 수 있다면 light, heavy 둘다 같이 idx 이동
아니라면 heavy만 idx이동
이동 후에는 answer 증가


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

using namespace std;

int solution(vector<int> people, int limit) {
    int answer = 0;
    sort(people.begin(), people.end());

    int light = 0;
    int heavy = people.size() - 1;

    // light = heavy인 경우 혼자 타고 나가는 경우
    while (light <= heavy) {
        // 가장 가벼운 사람과 무거운 사람이 제한 이하이면 +1
        if (people[light] + people[heavy] <= limit) {
            // 이때 가벼운 사람 타고 나갔으니 light idx++
            light++;
        }

        // 무거운 사람은 같이 타든 혼자타든 무조건 +1
        heavy--;
        // 보트 하나 추가
        answer++;
    }

    return answer;
}

0개의 댓글