본문 바로가기

problem solving

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

정렬을 한 후 가장작은 값의 위치(front)와 가장 큰 값의 위치(end)의 값을 더한 값이 limit보다 크다면

한 명밖에 못타기 때문에 end를 한칸 줄여 가장 큰 값을 하나 제거한다.

반대로 limit보다 작다면 두 명이 탈 수 있기에 front++, end--를한다.

#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 front = 0;
    int end = people.size() - 1;
    while(front <= end) {
        if (people[front+ people[end> limit) {
            end--;
            answer++;
        }
        else if (people[front+ people[end<= limit) {
            front++end--;
            answer++;
        }
    } 
    
    return answer;
}
cs

'problem solving' 카테고리의 다른 글

[프로그래머스]베스트앨범  (0) 2020.03.12
[프로그래머스]위장  (0) 2020.03.12
[프로그래머스]괄호 변환  (0) 2020.03.10
[프로그래머스]숫자 야구  (0) 2020.03.10
[프로그래머스]전화번호 목록  (0) 2020.03.10