본문 바로가기

코딩테스트 대비

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

구명보트 문제 ㄴㅇㄱ 

그리디 탐욕법 쓰라는데 걍 알고리즘 찾는 느낌인거같은데 뭔지도 이해가 안된다 진짜;

입력 값 vector<int> people, int limint

출력 값 int answer

프로세스

1. people 배열 오름차순으로 정렬하기

2. 최대값과 최소값의 합이 limit값보다 작거나 같으면 answer 값 하나씩 감소

 

풀이

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

using namespace std;

int solution(vector<int> people, int limit) {
    int answer = people.size();
    int min = 0;
    sort(people.begin(), people.end());
    
    for(int i=people.size()-1; i>min; i--){
        if(people[i]+people[min] <=limit){
            answer--;
            min++;
        }else{
        }
    }
        
    return answer;
}

 

limit 변수를 그냥 100으로 넣어버려서 한 한시간은 테스트케이스 작성에 쏟았다

 

다른분들의 코드를 봤는데 다 answer이 0이고 while문 사용해서 쭈글쭈글해서 테스트케이스 추가하면서 찾고있었는데

번뜩 보였다 하,,,,,ㅠ 넘 슬퍼ㅠ