SWEA - [d2] 1959 두 개의 숫자열

Esther·2022년 11월 19일
0

SWEA

목록 보기
24/46

N 개의 숫자로 구성된 숫자열 Ai (i=1~N) 와 M 개의 숫자로 구성된 숫자열 Bj (j=1~M) 가 있다.

아래는 N =3 인 Ai 와 M = 5 인 Bj 의 예이다.

Ai 나 Bj 를 자유롭게 움직여서 숫자들이 서로 마주보는 위치를 변경할 수 있다.

단, 더 긴 쪽의 양끝을 벗어나서는 안 된다.

서로 마주보는 숫자들을 곱한 뒤 모두 더할 때 최댓값을 구하라.

위 예제의 정답은 아래와 같이 30 이 된다.

[제약 사항]

N 과 M은 3 이상 20 이하이다.

[입력]

가장 첫 줄에는 테스트 케이스의 개수 T가 주어지고, 그 아래로 각 테스트 케이스가 주어진다.

각 테스트 케이스의 첫 번째 줄에 N 과 M 이 주어지고,

두 번째 줄에는 Ai,

세 번째 줄에는 Bj 가 주어진다.

[출력]

출력의 각 줄은 '#t'로 시작하고, 공백을 한 칸 둔 다음 정답을 출력한다.

(t는 테스트 케이스의 번호를 의미하며 1부터 시작한다.)

입력
10
3 5
1 5 3
3 6 -7 5 4
7 6
6 0 5 5 -1 1 6
-4 1 8 7 -9 3
...

출력
#1 30
#2 63
...

package prc_d2;

import java.util.Scanner;

public class P1959 {
	public static void main(String[] args) {
		Scanner sc = new Scanner(System.in);
		int T = sc.nextInt();
		for (int tc = 1; tc <= T; tc++) {
			int N = sc.nextInt();
			int M = sc.nextInt();

			int[] arr1 = new int[N];
			int[] arr2 = new int[M];

			for (int i = 0; i < N; i++) {
				arr1[i] = sc.nextInt();
			}
			for (int i = 0; i < M; i++) {
				arr2[i] = sc.nextInt();
			}

			int max = 0;
			if (N < M) {
				for (int i = 0; i < M - N + 1; i++) {
					int result = 0;
					for (int j = 0; j < N; j++) {
						result += arr1[j] * arr2[i + j];
					}
					max = Math.max(max, result);
				}
			}
			if (N > M) {
				for (int i = 0; i < N - M + 1; i++) {
					int result = 0;
					for (int j = 0; j < M; j++) {
						result += arr1[i + j] * arr2[j];
					}
					max = Math.max(max, result);
				}
			} else {
				int result = 0;
				for (int a = 0; a < N; a++) {
					result += arr1[a] + arr2[a];
				}
				max = Math.max(max, result);
			}
			System.out.println(max);

		}

	}

}

0개의 댓글