Problem Solving/Java
백준 1912 연속합 동적계획법 활용 풀이 ( Java )
TakeKnowledge
2019. 11. 1. 12:55
반응형
1912번: 연속합
첫째 줄에 정수 n(1 ≤ n ≤ 100,000)이 주어지고 둘째 줄에는 n개의 정수로 이루어진 수열이 주어진다. 수는 -1,000보다 크거나 같고, 1,000보다 작거나 같은 정수이다.
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
|
public class Main {
public static void main(String[] args) throws IOException {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(System.out));
int n = Integer.parseInt(br.readLine());
int d[] = new int[n];
// 숫자 저장
int a[] = new int[n];
// 연속합 저장
String[] words = br.readLine().split(" ");
for (int i = 0; i < words.length; i++) {
d[i] = Integer.parseInt(words[i]);
}
// 수 저장
a[0] = d[0];
// 첫 연속합은 처음 값 저장
for (int i = 1; i < d.length; i++) {
if (d[i] + a[i - 1] > d[i]) {
// i번째 숫자랑 그간의 연속합을 더해서 합한게 i번째 수보다 크면
a[i] = d[i] + a[i - 1];
// 더한 값을 연속합에 저장
} else {
// 아니면
a[i] = d[i];
// 단독 값을 연속합에 저장
}
}
int max = -1001;
for (int i : a) {
if (i > max) {
max = i;
}
}
// 마지막에 저장되어 있는 연속값을 출력
}
}
|
어떻게 풀어야할지만 알면 코드 구현은 어렵지 않은데
그 어떻게 풀어야할지를 생각해내는 능력을 어떻게 길러야 할지 모르겠다..
반응형