0
0

More than 1 year has passed since last update.

paizaラーニング レベルアップ問題集 線形探索メニュー応用編 JavaScript 大小関係

Posted at

大小関係 (paizaランク B 相当)

解答例

問題文の

連続する 3 要素 a_i, a_{ i + 1 }, a_{ i + 2 } が、 a_i < a_{ i + 1 } > a_{ i + 2 } または a_i > a_{ i + 1 } < a_{ i + 2 } となる i の個数を出力

に基づいて実装します。

const fs = require("fs");
const input = fs.readFileSync("/dev/stdin", "utf-8").trim();
const lines = input.split("\n");

const [n] = lines[0].split(" ").map(Number);
const a = lines[1].split(" ").map(Number);

let count = 0;//連続する三要素の区間の個数

for (let l = 0; l < n - 2; l++) {//aについて調べる区間の左端l
  if (a[l] < a[l + 1] && a[l + 1] > a[l + 2] ||
      a[l] > a[l + 1] && a[l + 1] < a[l + 2])
  {
    count += 1;
  }
}
console.log(count);
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