[BOJ] 11659번: 구간 합 구하기 4 (JavaScript)

2024년 7월 22일

문제

11659: 구간 합 구하기 4

문제 설명

수 N개가 주어졌을 때, i번째 수부터 j번째 수까지 합을 구하는 프로그램을 작성하시오.

입력

첫째 줄에 수의 개수 N과 합을 구해야 하는 횟수 M이 주어진다. 둘째 줄에는 N개의 수가 주어진다. 수는 1,000보다 작거나 같은 자연수이다. 셋째 줄부터 M개의 줄에는 합을 구해야 하는 구간 ij가 주어진다.

출력

M개의 줄에 입력으로 주어진 i번째 수부터 j번째 수까지 합을 출력한다.

제한

  • 1 ≤ N ≤ 100,000
  • 1 ≤ M ≤ 100,000
  • 1 ≤ ijN

입출력

입력

5 3
5 4 3 2 1
1 3
2 4
5 5

출력

12
9
1

코드

const input = require('fs')
.readFileSync(process.platform === 'linux' ? '/dev/stdin' : './input.txt')
.toString()
.trim()
.split('\n');
const list = input[1].split(' ').map(Number);
const testCase = input.slice(2).map(val => val.split(' ').map(Number));
const answer = [];
const totalSum = [0];
let tmp = 0;
for (const num of list) {
tmp += num;
totalSum.push(tmp);
}
for (const [start, end] of testCase) {
answer.push(totalSum[end] - totalSum[start - 1]);
}
console.log(answer.join('\n'));

reduce 메서드 활용 풀이

const input = require('fs')
.readFileSync(process.platform === 'linux' ? '/dev/stdin' : './input.txt')
.toString()
.trim()
.split('\n');
const list = input[1].split(' ').map(Number);
const testCase = input.slice(2).map(val => val.split(' ').map(Number));
const totalSum = list.reduce(
(acc, cur) => {
acc.push(acc[acc.length - 1] + cur);
return acc;
},
[0],
);
const answer = testCase.reduce((acc, [start, end]) => {
acc.push(totalSum[end] - totalSum[start - 1]);
return acc;
}, []);
console.log(answer.join('\n'));

11659-result

시간과 메모리가 약간 감소했다.

Kihoon
기록하는 프론트엔드 개발자

이전 포스트
[BOJ] 17086번: 아기상어2 (JavaScript)
다음 포스트
[BOJ] 1431번: 시리얼 번호 (JavaScript)