본문 바로가기

CS/프로그래머스

프로그래머스 - level 3/최고의 집합/C++


해결방법

  • 문제 설명에 두 가지 조건이 있는데, 그중 두 번째 조건인 "위 조건을 만족하면서 각 원소의 곱이 최대가 되는 집합"이라는 것에 힌트를 얻을 수 있음
  • 원소의 곱이 최대 → 나눗셈을 활용하여 해결
  • 원소들의 합(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;
}