1
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

今回は paiza の「累積和の計算」の問題に挑戦!
新しいシリーズに突入!


🧩 問題概要

  • 長さ N の数列 A が与えられる
  • i(1〜N)について、先頭から i 番目までの合計 を求める

入力

  • 1行目:数列の長さ N
  • 2行目:数列 A_1 ~ A_N

出力

  • S_1 から S_N までを 1行ずつ出力



入力例:

10
0 1 2 3 4 5 6 7 8 9

出力例:

0
1
3
6
10
15
21
28
36
45






✅OK例:

const rl = require('readline').createInterface({ input: process.stdin });

const lines = [];

rl.on('line', (inputLine) => lines.push(inputLine));

rl.on('close', () => {
    const N = Number(lines[0]);
    const arrA = lines[1].split(' ').map(Number);
    
    let prefixSum = 0; // 累積和
    
    for (let i = 0; i < N; i++) {
        prefixSum += arrA[i];
        console.log(prefixSum);
    }
});

🔍 コードの流れ

  • readline を使って 標準入力を1行ずつ読み込む
  • 入力された各行を配列 lines に保存する
  • 入力がすべて読み終わったら close が呼ばれる

  • 1行目から 数列の長さ N を取得する
  • 2行目から 数列 A を配列 arrA として取得する

  • 変数 prefixSum0 で初期化する
    → これが 累積和(今までの合計)

  • i = 0 から N-1 までループする
    • arrA[i]prefixSum に足す
    • 現在の累積和 prefixSum を出力する





📝まとめ

  • 累積和:先頭からの合計を順に更新
  • 毎回 A_1 + ... + A_i を計算し直さない
  • prefixSum += A[i] が累積和の更新
1
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?