https://school.programmers.co.kr/learn/courses/30/lessons/42885
탐욕법(그리디)
알고리즘
https://velog.io/@contea95/%ED%83%90%EC%9A%95%EB%B2%95%EA%B7%B8%EB%A6%AC%EB%94%94-%EC%95%8C%EA%B3%A0%EB%A6%AC%EC%A6%98
people을 내림차순으로 정렬한 뒤 반복문을 돌리는데 맨 앞의 수(가장 큰 수) 부터 검사해 나간다.
1. 맨 앞의 수와 맨 뒤의 수의 합이 limit 보다 작거나 같을 경우
answer++ 하고 맨 앞과 맨 뒤의 다음 수를 검사시작한다. i++, j--
2. limit보다 클 경우
answer++ 하고 맨 앞의 다음 수를 검사시작한다. i++
#include <string>
#include <vector>
#include <algorithm>
using namespace std;
int solution(vector<int> people, int limit) {
int answer = 0;
sort(people.rbegin(), people.rend());
int sub = 0;
int j = people.size() - 1;
for(int i = 0; i <= j;)
{
sub = limit - people[i];
if(people[j] <= sub)
{
answer++;
i++;
j--;
}
else
{
answer++;
i++;
}
}
return answer;
}
#include <string>
#include <vector>
#include <algorithm>
using namespace std;
int solution(vector<int> people, int limit) {
sort(people.begin(), people.end());
reverse(people.begin(), people.end());
int N = (int)people.size();
int res = 0;
for (int i = 0, j = N - 1; i <= j; i++) {
if (people[i] + people[j] <= limit) {
j--;
}
res++;
}
return res;
}
방식은 같다. 다만 내 풀이에서 반복문 내부의 if else 문에서 if던 else던 결국 answer++, i++ 하는 것은 똑같으므로 묶어내어 코드를 줄일 수 있다.