728x90
문제
매일 아침 9시에 학교에서 측정한 온도가 어떤 정수의 수열로 주어졌을 때, 연속적인 며칠 동안의 온도의 합이 가장 큰 값을 알아보고자 한다.
예를 들어, 아래와 같이 10일 간의 온도가 주어졌을 때,
3 -2 -4 -9 0 3 7 13 8 -3
모든 연속적인 이틀간의 온도의 합은 아래와 같다.
이때, 온도의 합이 가장 큰 값은 21이다.
또 다른 예로 위와 같은 온도가 주어졌을 때, 모든 연속적인 5일 간의 온도의 합은 아래와 같으며,
이때, 온도의 합이 가장 큰 값은 31이다.
매일 측정한 온도가 정수의 수열로 주어졌을 때, 연속적인 며칠 동안의 온도의 합이 가장 큰 값을 계산하는 프로그램을 작성하시오.
입력
첫째 줄에는 두 개의 정수 N과 K가 한 개의 공백을 사이에 두고 순서대로 주어진다. 첫 번째 정수 N은 온도를 측정한 전체 날짜의 수이다. N은 2 이상 100,000 이하이다. 두 번째 정수 K는 합을 구하기 위한 연속적인 날짜의 수이다. K는 1과 N 사이의 정수이다. 둘째 줄에는 매일 측정한 온도를 나타내는 N개의 정수가 빈칸을 사이에 두고 주어진다. 이 수들은 모두 -100 이상 100 이하이다.
출력
첫째 줄에는 입력되는 온도의 수열에서 연속적인 K일의 온도의 합이 최대가 되는 값을 출력한다.
연속적인 K개의 합을 비교하기 위해서, 처음부터 K-1까지의 합을 구한다.
그리고 index가 하나 증가할 때마다 새로 추가할 값을 더하고 연속된 수에서 가장 앞의 값을 빼준다.
이 중 가장 큰 값을 결과로 출력한다.
package Silver.s3;
import java.util.Scanner;
public class BOJ_2559_수열 {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int N = sc.nextInt();
int K = sc.nextInt();
int[] arr = new int[N];
for (int i = 0; i < N; i++) {
arr[i] = sc.nextInt();
}
// K개의 합, index가 1 증가할 때마다 새로운 값 - 맨 앞 값만큼 sum이 변함
int sum = 0;
for (int i = 0; i < K; i++) {
sum += arr[i];
}
int idx = K;
int tmp = sum;
while (idx < N) {
tmp = tmp + arr[idx] - arr[idx - K];
sum = Math.max(sum, tmp);
idx++;
}
System.out.println(sum);
}
}
728x90
'문제 풀이 > BOJ' 카테고리의 다른 글
[백준] 17298 - 오큰수 (자바/Java) (0) | 2022.08.18 |
---|---|
[백준] 1874 - 스택수열 (자바/Java) (0) | 2022.08.18 |
[백준] 2304 - 창고 다각형 (자바/Java) (0) | 2022.08.18 |
[백준] 1158 - 요세푸스 문제 (자바/Java) (0) | 2022.08.18 |
[백준] 4949 - 균형잡힌 세상 (자바/Java) 스택 Stack (0) | 2022.08.16 |