PS/백준

백준 / 누적 합 / 11659번 / 구간 합 구하기 4 / JS

KimMinJun 2023. 1. 16. 12:24

< 문제 바로가기 >

 

11659번: 구간 합 구하기 4

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

www.acmicpc.net

 

const fs = require('fs');
const filePath = process.platform === 'linux' ? '/dev/stdin' : '../input.txt';
// const filePath = process.platform === 'linux' ? '/dev/stdin' : 'BOJ/input.txt';
const input = fs.readFileSync(filePath).toString().trim().split('\n');

const [N, M] = input.shift().split(' ').map(Number);
const NUMBER_LIST = input.shift().split(' ').map(Number);
const PART_LIST = input.map(el => el.split(' ').map(Number));

function solution() {
  let result = [];
  let accumulationList = Array.from({ length: NUMBER_LIST.length + 1 }, () => 0);

  NUMBER_LIST.forEach((el, idx) => {
    accumulationList[idx + 1] = accumulationList[idx] + el;
  });

  for(const [START, END] of PART_LIST) {
    result.push(accumulationList[END] - accumulationList[START - 1]);
  }

  console.log(result.join('\n'));
}

solution();

사실 로직은 맞았는데 계속 시간초과가 떠서 의아해했던 문제이다.

서칭해본 결과 JS의 console.log가 여러번 반복되어서 시간초과가 났다.

그래서 result 배열에 모든 output 결과값을 push 해준 후에, 마지막에 개행문자로 join해서 한번에 출력해주었다.