[BOJ] 구간합 구하기4

박신희·2022년 8월 3일
0

[풀이] BOJ

목록 보기
3/7
post-thumbnail

❗ 풀이과정

  • 구간합을 사용하여 시간을 많이 절약했다.
    💫 구간 합
    arr = [0,1,2,3,4] 의 합을 구하려면,
    먼저, 각각 누적합을 먼저 구한다.
    prefix_sum = [0,1,3,6,10] 인덱스가 0부터 시작한다고 했을 때,
    인덱스 2부터 3까지의 합은 (2+3)=5 인데,
    prefix_sum 으로 prefix_sum[3]-prefix_sum[(2-1)] 와 같다.

🤜 풀이코드

import java.util.Scanner;

public class Main{

	public static void main(String[] args) {
		Scanner sc = new Scanner(System.in);
		int N = sc.nextInt();
		int T = sc.nextInt();
		int [] arr = new int [N+1];
		int tmp =0;
		arr[0]=tmp;
		for(int n=1;n<=N;n++) {
			tmp 	+= sc.nextInt();
			arr[n]	= tmp;
		}

		for(int t=0;t<T;t++) {
			int start=sc.nextInt()-1;
			int end=sc.nextInt();
			
			System.out.println(arr[end]-arr[start]);
		}
	}
}
profile
log my moments 'u')/

0개의 댓글