Algorithm/Baekjoon
[Algorithm]Baekjoon 10211번 : Maximum Subarray
MaxLevel
2024. 3. 20. 04:33
https://www.acmicpc.net/problem/10211
10211번: Maximum Subarray
크기 N인 정수형 배열 X가 있을 때, X의 부분 배열(X의 연속한 일부분) 중 각 원소의 합이 가장 큰 부분 배열을 찾는 Maximum subarray problem(최대 부분배열 문제)은 컴퓨터 과학에서 매우 잘 알려져 있
www.acmicpc.net
|
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
46
47
48
49
50
51
52
53
54
|
#include <iostream>
#include <string>
#include <map>
#include <vector>
#include <algorithm>
#include <math.h>
#include <queue>
#include <functional>
#include <sstream>
#include <memory.h>
#include <deque>
#include <set>
#include <unordered_map>
#include <stack>
#include <numeric>
using namespace std;
int t, n;
int main()
{
ios::sync_with_stdio(false);
cin.tie(0);
cout.tie(0);
cin >> t;
while (t--)
{
cin >> n;
vector<int> v(n);
int maximumSubarray = -1001;
for (int i = 0; i < n; ++i)
{
cin >> v[i];
}
for (int i = 0; i < n; ++i)
{
int sum = 0;
for (int j = i; j < n; ++j)
{
sum += v[j];
maximumSubarray = max(maximumSubarray, sum);
}
}
cout << maximumSubarray << endl;
}
}
|
cs |
최대 연속된 부분수열의 합을 구하는 문제이다.
가장 기본적인 n^2 풀이이다.
n값이 최대 1,000밖에 안되서 가능하긴한데, 되도록 n^2풀이보다는 n 풀이를 이해해놓는게 좋다.
|
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
46
47
48
49
50
51
52
53
54
|
#include <iostream>
#include <string>
#include <map>
#include <vector>
#include <algorithm>
#include <math.h>
#include <queue>
#include <functional>
#include <sstream>
#include <memory.h>
#include <deque>
#include <set>
#include <unordered_map>
#include <stack>
#include <numeric>
using namespace std;
int t, n;
int main()
{
ios::sync_with_stdio(false);
cin.tie(0);
cout.tie(0);
cin >> t;
while (t--)
{
cin >> n;
vector<int> v(n);
int maximumSubarray = -1000001;
int sum = 0;
for (int i = 0; i < n; ++i)
{
cin >> v[i];
sum += v[i];
maximumSubarray = max(maximumSubarray, sum);
if (sum < 0)
{
sum = 0;
}
}
cout << maximumSubarray << endl;
}
}
|
cs |
기본적으로 sum에다가 원소를 누적시킨 후, 최대값을 바로 갱신시켜준다.
그다음에 sum값이 0 이하일 경우, 즉 음수라면 사실상 이 누적값을 계속 유지시킬 이유가 전혀 없다.
그 다음수가 음수든 양수든, 해당 인덱스부터 다시 누적을 시작하면 되기 때문이다.