0
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?

「PV調査」を解くために:part4

Posted at

今回は paiza の「「PV調査」を解くために:part4」の問題に挑戦!


問題概要

  • ウェブサイトの訪問データを持っている。
  • 連続する k 日間の合計訪問者数」がすでに計算されており、
    その中で 最も訪問者数が多かった期間のうち、一番早い開始日 を求める。

つまり:

  • b_i は「i日目から i+k−1日目までの合計訪問者数」
    その中で 最大の b_i を探し、
    その最大値が最初に現れた i を出力する問題。



入力例:

8 3 // n k
13 9 11 14 19 20 // b_i

出力例:

6






✅ OK例:

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

const lines = [];

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

rl.on('close', () => {
    const [n, k] = lines[0].split(' ').map(Number);
    const b = lines[1].split(' ').map(Number);
    
    let ans = 1;
    let max = null;
    
    for (let i = 0; i < n - k + 1; i++) {
        if (b[i] > max) {
            max = b[i];
            ans = i+1;
        }
    }
    
    console.log(ans);
});

🧩 コードの流れ

  1. 入力を受け取る
    • 1行目 → n, k を取得
    • 2行目 → 連続する k 日間の合計訪問者数の配列 b を取得
  2. 初期設定
    • ans = 1:最初の開始日(1日目)を仮の答えとして設定
    • max = null:まだ最大値が決まっていない状態で初期化
  3. ループで最大値を探索
    • for (let i = 0; i < n - k + 1; i++)
      • b[i]i番目の合計訪問者数)を確認
      • b[i] > max のとき:
        • max を更新(新しい最大値)
        • ans にその開始日 i+1 を代入(1始まりのため)
  4. 結果を出力
    • 最も合計訪問者数が多かった 最初の開始日(1-indexed)を出力






🗒️ まとめ

  • 配列の最大値探索
    if (b[i] > max) { max = b[i]; ans = i + 1; }
  • 「最初の出現」を優先したいとき
    >= ではなく > を使うのがポイント。
  • 1-indexed(1日目スタート) に注意して i+1




僕の失敗談(´;ω;`)と解決法🐈

0
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
0
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?