Notice
Recent Posts
Recent Comments
Link
«   2025/04   »
1 2 3 4 5
6 7 8 9 10 11 12
13 14 15 16 17 18 19
20 21 22 23 24 25 26
27 28 29 30
Archives
Today
Total
관리 메뉴

hwooo

프로그래머스 (C/C++, Java) 12938 : 최고의 집합 본문

Study/Algorithm

프로그래머스 (C/C++, Java) 12938 : 최고의 집합

hwooo 2024. 12. 12. 13:30


풀이

원소들의 곱이 최대가 되려면 원소들 간의 크기 차이가 최소로 나야 한다.

따라서 주어진 s를 n으로 나눠 크기가 n인 배열을 만들었고, 나머지는 각 원소에 1씩 값을 더하여 배열을 구성했다.

더하는 작업을 끝 인덱스부터 했기에 불가능한 경우의 수는 answer[0]의 값이 0인지를 확인하여 반환했다.


C/C++ 코드

#include <string>
#include <vector>

using namespace std;

vector<int> solution(int n, int s) {
    // s / n 을 원소로 가진 크기가 n인 집합 생성
    int div = s / n;
    vector<int> answer(n, s / n);

    // 나머지가 없다면 바로 리턴
    if (s % n == 0)
        return answer;

    // 나머지만큼의 원소 갯수에 각각 1씩 더함
    else {
        int rem = s - s / n * n;
        int idx = n - 1;
        while (rem--)
            answer[idx--]++;
    }
    
    // 0번째 인덱스에 값이 있다면 answer 반환
    if (answer[0])
        return answer;
    
    return {-1};
}

 

Java 코드

import java.util.*;

class Solution {
    public int[] solution(int n, int s) {
        
        // s / n 을 원소로 가진 크기가 n인 집합 생성
        int[] answer = new int[n];
        Arrays.fill(answer, s / n);
        
        int remain = s - s / n * n;
        int idx = n - 1;
        
        // 나머지가 있다면 원소당 1씩 추가해 나머지를 채움
        while (remain-- > 0)
            answer[idx--]++;
        
        // 첫번째 원소가 0이라면 s를 만들 수 없으므로 -1 반환
        if (answer[0] == 0)
            return new int[] {-1};
        return answer;
    }
}