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?

More than 1 year has passed since last update.

加算された数列の最大値 .entries() -Infinity

0
Posted at

Paizaの「a[i] + i の最大値を求める」問題に挑戦したときの学習を記録!


問題概要

  • N 個の整数 a_1, a_2, …, a_N が与えられる。
  • a_i に i を足したとき、a_1 , … , a_N の最大値を出力せよ。

入力例:

5
1 2 3 4 5

出力例:

10




✅ OK例:Math.max() + 配列

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

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


rl.on('close', () => {
    const N = Number(lines[0]);
    const nums = lines[1].split(' ').map(Number);
    
    let sum = [];
    for(let i = 1; i <= N; i++){
        sum.push(nums[i-1] + i);
    }
    
    console.log(Math.max(...sum));
});

.push() で計算結果を全部入れてから Math.max(...sum) で最大値を取るやり方。
これは「結果を配列に残したい」ってときに便利。


💡 .entries()

インデックスも値も同時にほしいときは .entries() を使うと良い!

for-of だと通常「値」しか取れないけど、

.entries() は [インデックス, 値] のペアを返してくれるから、

for(const [index, value] of nums.entries()) {
    sum.push(value + index + 1);
}

って書ける。 index は 0 始まりだから +1 して i に合わせてるよ。




✅ sum 配列なしでも最大値だけでOK!

実は、最大値だけほしいなら sum 配列すらいらない。直接更新しながら最大値を求める方法がスマート!

let maxVal = -Infinity;
for(let i = 1; i <= N; i++) {
    const current = nums[i - 1] + i;
    if(current > maxVal) {
        maxVal = current;
    }
}
console.log(maxVal);

-Infinity って「どんな数よりも小さい」特別な値。

これを使うと「最初に比べる相手がいない」ってときに超便利。順に比べながら更新していくやつだね!




📝 メモ

  • 配列インデックスは 0 から始まるけど、問題は 1 から始まる。ズレに注意!
  • .entries() は配列操作で「インデックスと値」を同時に扱うのに超便利。
  • 最大値だけほしいなら「一時配列 sum を作らず、比較しながら更新」でOK!
  • 最小値スタートの -Infinity は「どんな数よりも小さい」という覚え方でイメージしやすい。




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

0
0
1

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?