[백준 11659] 구간 합 구하기4

JOY·2023년 4월 16일
0

[CodingTest] Java

목록 보기
24/61
post-thumbnail

😊 문제

백준 11659 - 구간 합 구하기 4

😊 코드


import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.StringTokenizer;

public class Main {

	public static void main(String[] args) throws IOException {
		BufferedReader bf = new BufferedReader(new InputStreamReader(System.in));
		StringTokenizer st = new StringTokenizer(bf.readLine(), " ");

		int N = Integer.parseInt(st.nextToken()); // 수의 개수
		int M = Integer.parseInt(st.nextToken()); // 합을 구해야 하는 횟수

		int[] S = new int[N + 1];

		st = new StringTokenizer(bf.readLine());
		for (int i = 1; i <= N; i++) {
			S[i] = S[i - 1] + Integer.parseInt((st.nextToken()));
		}

		for (int x = 0; x < M; x++) {
			st = new StringTokenizer(bf.readLine());
			int i = Integer.parseInt(st.nextToken());
			int j = Integer.parseInt(st.nextToken());

			System.out.println(S[j] - S[i - 1]);
		}

	}

}

😊 풀이

수 N개가 주어졌을 때, i번째 수부터 j번째 수까지 합을 구하는 문제

합 배열 공식 : S[i] = S[i-1] + A[i]
구간합 공식 : S[j] - S[i-1] (구간 i~j가 주어졌을 때)

profile
Just Do IT ------- 🏃‍♀️

0개의 댓글

Powered by GraphCDN, the GraphQL CDN