백준 11659번 - 구간 합 구하기
2025. 4. 7. 21:32

풀이-1

import java.util.Scanner;

public class Main_11659 {

	public static void main(String[] args) {
	   Scanner scan = new Scanner(System.in);
	   int N = scan.nextInt();//수의 개수
	   int M = scan.nextInt();//구해야 하는 횟수
	   
	   int[]arr = new int[N+1];
	   
	   //데이터 입력
	   for(int i=1; i<=N; i++) {
		   arr[i] = scan.nextInt();
	   }
	   
	   //구간합 구하기
	   for(int i=0; i<M; i++) {
		   int begin = scan.nextInt();
		   int end = scan.nextInt();
		   
		   int sum=0;
		   for(int j=begin; j<=end; j++) {
			   sum+=arr[j];
		   }
		   System.out.println(sum);
		   
	   }	   
       scan.close();
	}//main

}

풀이-2

import java.util.Scanner;

public class Main_11659_v2 {

	public static void main(String[] args) {
	   Scanner scan = new Scanner(System.in);
	   int N = scan.nextInt();//수의 개수
	   int M = scan.nextInt();//구해야 하는 횟수
	   
	   int[]arr = new int[N+1];
	   
	   //데이터 입력
	   for(int i=1; i<=N; i++) {
//		   arr[i] = scan.nextInt();
		   arr[i] = arr[i-1]+scan.nextInt();
	   }
	   
	   //구간합 구하기
	   for(int i=0; i<M; i++) {
		   int begin = scan.nextInt();
		   int end = scan.nextInt();
		   
//		   int sum=0;
//		   for(int j=begin; j<=end; j++) {
//			   sum+=arr[j];
//		   }
//		   System.out.println(sum);
		   System.out.println(arr[end]-arr[begin-1]);
		   
	   }	   
       scan.close();
	}//main

}

'코딩테스트' 카테고리의 다른 글

순열(Permutation) 예제  (0) 2025.04.08
순열(Permutation)  (0) 2025.04.08
백준 11382번 - 꼬마 정민  (0) 2025.04.07
백준 1000번 A+B  (0) 2025.04.07
StringBuilderStringTokenizer  (0) 2025.04.07