본문 바로가기

알고리즘/KOALA 알고리즘 스터디

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

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

 

구명보트는 한번에 2명만 탑승 가능하며 limit 제한이 있고 구명보트를 최소한의 수로 사용해야한다. 그렇다면 보트를 이용할 때 최대한 limit에 가깝게 탑승해야한다! 정렬 후 투포인터를 사용하여 혼자 타야하는 사람, 툴이 탈 수 있는 가장 적합한 사례를 구하여 답을 풀었다.

 

#include<iostream>
#include <string>
#include <algorithm>
#include <vector>
using namespace std;

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

    int left = 0;
    int right = people.size() - 1;

    while (left <= right) {
        if (people[left] + people[right] <= limit) {
            // 두명 탑승
            left++;   
            right--;  
        } else {
            // 혼자 탑승
            right--;
        }
        answer++; 
    }

    return answer;
}