

해결방법
- 문제 설명에 두 가지 조건이 있는데, 그중 두 번째 조건인 "위 조건을 만족하면서 각 원소의 곱이 최대가 되는 집합"이라는 것에 힌트를 얻을 수 있음
- 원소의 곱이 최대 → 나눗셈을 활용하여 해결
- 원소들의 합(s)을 원소의 개수(n)으로 나눠 몫을 구하면 원소 1개를 구할 수 있음
- 그러면 s에서 위에서 구한 원소 1개를 빼주면 (s -= div) 나머지 원소도 구할 수 있음
- n > s인 경우(예시의 n=2, s=1)에 대한 예외 처리도 추가해 주면 됨
코드
#include <string>
#include <vector>
#include <algorithm>
#include <iostream>
using namespace std;
vector<int> solution(int n, int s) {
vector<int> answer;
if(n>s) {
answer.push_back(-1);
return answer;
}
while(n > 0)
{
int div = s/n;
answer.push_back(div);
s -= div;
n--;
}
sort(answer.begin(), answer.end());
return answer;
}
'CS > 프로그래머스' 카테고리의 다른 글
프로그래머스 - level3/베스트 앨범/C++ (2) | 2023.05.17 |
---|---|
프로그래머스 - level2/가장큰수/C++ (0) | 2023.05.15 |
프로그래머스 - 탐욕법(Greedy)/체육복/C++ (0) | 2021.08.02 |
프로그래머스 - 완전탐색/모의고사/C++ (0) | 2021.07.30 |
프로그래머스 - 정렬/k번째수/C++ (0) | 2021.07.28 |