강의로 돌아가기
선종연

이게 왜 시간초과인가요?

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

using namespace std;

int solution(vector<int> budgets, int M) {
    int answer = 0;
    int n = budgets.size();
    sort(budgets.begin(), budgets.end());
    vector<int> dp(n);
    int index = 0;
    int sum = 0;
    for (int x: budgets) {
        sum += x;
        dp[index] = sum;
        index++;
    }

    bool isAllCover = true;
    for (int i = -1; i < n - 1; i++) {

        int remain;
        if (i == -1) {
            remain = M;
        } else remain = M - dp[i];

        int avg = remain / (n - 1 - i);
        if (i == -1 && avg < budgets[i + 1]) {
            answer = avg;
            isAllCover = false;
            break;
        }
        if (i >= 0 && budgets[i] <= avg && avg < budgets[i + 1]) {
            answer = avg;
            isAllCover = false;
            break;
        }


    }


    return isAllCover ? budgets[n - 1] : answer;
}
작성중인 코드―solution.cpp
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
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
#include <string>
#include <vector>
#include <algorithm>

using namespace std;

int solution(vector<int> budgets, int M) {
    int answer = 0;
    int n = budgets.size();
    sort(budgets.begin(), budgets.end());
    vector<int> dp(n);
    int index = 0;
    int sum = 0;
    for (int x: budgets) {
        sum += x;
        dp[index] = sum;
        index++;
    }

    bool isAllCover = true;
    for (int i = -1; i < n - 1; i++) {

        int remain;
        if (i == -1) {
            remain = M;
        } else remain = M - dp[i];

        int avg = remain / (n - 1 - i);
        if (i == -1 && avg < budgets[i + 1]) {
            answer = avg;
            isAllCover = false;
            break;
        }
        if (i >= 0 && budgets[i] <= avg && avg < budgets[i + 1]) {
            answer = avg;
            isAllCover = false;
            break;
        }


    }


    return isAllCover ? budgets[n - 1] : answer;
}
0 개의 답변
답변 쓰기
이 입력폼은 마크다운 문법을 지원합니다. 마크다운 가이드 를 참고하세요.