구간 합은 합 배열을 이용하여 시간 복잡도를 더 줄이기 위해 사용하는 특수한 목적의 알고리즘이다.
합 배열의 S 정의
S[i] = A[0] + A[1] + A[2] + ... + A[i-1] + A[i]
합 배열 S를 만드는 공식
S[i] = S[i-1] + A[i]
구간 합을 구하는 공식
S[i] - S[i-1]
import java.util.Scanner;
public class P11659_구간합구하기 {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int N = sc.nextInt();
int M = sc.nextInt();
int[] sum = new int[N + 1];
sum[0] = 0;
for (int i = 1; i <= N; i++) {
sum[i] = sc.nextInt() + sum[i - 1];
}
while (M-- > 0) {
System.out.println((-sum[sc.nextInt()-1]+sum[sc.nextInt()]));
}
}
}

import java.util.Scanner;
public class P2018_수들의합 {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int N = sc.nextInt();
int sum = 0;
int count = 1;
int start_index = 0, end_index = 0;
while (end_index != N) {
if (sum == N) {
count++;
end_index++;
sum += end_index;
} else if (sum > N) {
sum -= start_index;
start_index++;
} else if (sum < N) {
end_index++;
sum += end_index;
}
}
System.out.println(count);
}
}

import java.io.*;
import java.util.StringTokenizer;
public class P1940_주몽 {
public static void main(String[] args) throws IOException {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
int count = 0;
int N = Integer.parseInt(br.readLine());
int M = Integer.parseInt(br.readLine());
String sNum = br.readLine();
StringTokenizer st = new StringTokenizer(sNum);
int[] aa = new int[N];
for (int i = 0; i < N; i++) {
aa[i] = Integer.parseInt(st.nextToken());
}
int start_index = 0;
int end_index = 0;
for (int i = 0; i < N; i++) {
for (int j = i + 1; j < N; j++) {
start_index = aa[i];
end_index = aa[j];
if (start_index + end_index == M)
count++;
}
}
System.out.println(count);
}
}
