728x90
오답 노트 & 새로 알게 된 점
두 포인터의 기본 문제이다.
처음에 배열의 처음부터 K까지의 값을 더해준다.
그리고 나서 s와 e를 하나씩 늘리면서 A[s]는 빼주고, A[e]는 더해주면서 최대값을 구하면 된다.
코드
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
|
package TwoPointers;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.StringTokenizer;
public class BOJ2559 {
static int atoi(String str) {
return Integer.parseInt(str);
}
static int N, K;
static int A[];
public static void main(String[] args) throws IOException {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
StringTokenizer st = new StringTokenizer(br.readLine());
N = atoi(st.nextToken());
K = atoi(st.nextToken());
A = new int[N + 1];
st = new StringTokenizer(br.readLine());
for (int i = 1; i <= N; i++) {
A[i] = atoi(st.nextToken());
}
pro();
}
static void pro() {
int s = 1, e = K, sum = 0, rel = Integer.MIN_VALUE;
for (int i = 1; i <= K; i++) {
sum += A[i];
}
rel = Math.max(rel, sum);
while (e + 1 <= N) {
sum = sum - A[s++] + A[++e];
rel = Math.max(rel, sum);
}
System.out.println(rel);
}
}
|
cs |
728x90
'BOJ(Java)' 카테고리의 다른 글
자바(백준) 11728 배열 합치기 (0) | 2021.09.22 |
---|---|
자바(백준) 15565 귀여운 라이언 (0) | 2021.09.22 |
자바(백준) 2470 두 용액 (0) | 2021.09.22 |
자바(백준) 1806 부분합 (0) | 2021.09.21 |
자바(백준) 17266 어두운 굴다리 (0) | 2021.09.13 |