강의로 돌아가기

### 이게 왜 시간초과인가요?

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

using namespace std;

int solution(vector<int> budgets, int M) {
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]) {
isAllCover = false;
break;
}
if (i >= 0 && budgets[i] <= avg && avg < budgets[i + 1]) {
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 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]) {
isAllCover = false;
break;
}
if (i >= 0 && budgets[i] <= avg && avg < budgets[i + 1]) {
isAllCover = false;
break;
}

}

return isAllCover ? budgets[n - 1] : answer;
}
``````