Official

A - 山脈のジグザグ / Zigzag of Mountain Range Editorial by admin Editorial for printing

GPT 5.2 High

Overview

Given an elevation sequence \(R_1, R_2, \ldots, R_N\), count the number of positions where three consecutive points \((R_i, R_{i+1}, R_{i+2})\) form a “goes up then down” or “goes down then up” pattern (zigzag).

Analysis

The zigzag definition only needs to be checked for each group of three consecutive elements. For each position \(i\), we simply check whether one of the following holds: - \(R_i < R_{i+1} > R_{i+2}\) (peak shape) - \(R_i > R_{i+1} < R_{i+2}\) (valley shape)

In other words, there is no need to examine the complex structure of the entire array or detect peaks and valleys collectively. Since each \(i\) can be determined locally (using only 3 elements), it suffices to check sequentially from \(i=1\) to \(N-2\).

A naive approach that examines “all intervals” or “all combinations” would be \(O(N^2)\) or worse, which is too slow for \(N \le 2 \times 10^5\). However, since the elements to check are always fixed at length 3, a single scan solves it in \(O(N)\).

Concrete examples: - \([1, 3, 2]\): \(1<3>2\), so it is a zigzag - \([5, 2, 4]\): \(5>2<4\), so it is a zigzag - \([1, 2, 3]\): monotonically increasing, satisfies neither condition, so it is not a zigzag

Algorithm

  1. Initialize the answer \(ans=0\).
  2. Loop \(i\) from \(0\) to \(N-3\) (or from \(1\) to \(N-2\) in 1-indexed).
  3. Let \(a=R_i, b=R_{i+1}, c=R_{i+2}\):
    • If \((a < b > c)\) or \((a > b < c)\), increment \(ans\) by \(1\).
  4. Output \(ans\).

This check becomes intuitive when viewed as: “Is the middle element \(b\) larger than both neighbors (peak)?” or “Is the middle element \(b\) smaller than both neighbors (valley)?”

Complexity

  • Time complexity: \(O(N)\) (only a constant number of comparisons per \(i\))
  • Space complexity: \(O(N)\) (to store the elevation sequence)

Implementation Notes

  • The loop range should be \(i=0 \ldots N-3\) (i.e., \(N-2\) iterations) so that three consecutive points can always be accessed.

  • In Python, chained comparisons like (a < b > c) can be written directly and are easy to read (equivalent to a < b and b > c).

  • Since the input can be up to \(2 \times 10^5\) elements, using sys.stdin.buffer.read() allows for faster input reading.

    Source Code

import sys

def main():
    data = list(map(int, sys.stdin.buffer.read().split()))
    n = data[0]
    r = data[1:1+n]

    ans = 0
    for i in range(n - 2):
        a, b, c = r[i], r[i+1], r[i+2]
        if (a < b > c) or (a > b < c):
            ans += 1
    print(ans)

if __name__ == "__main__":
    main()

This editorial was generated by gpt-5.2-high.

posted:
last update: