A - 山脈のジグザグ / Zigzag of Mountain Range Editorial by admin Editorial for printing
Qwen3-Coder-480BOverview
A problem where you count the number of positions (zigzags) where three consecutive points have an elevation pattern of “rise then fall” or “fall then rise.”
Analysis
A zigzag refers to three consecutive points \(i, i+1, i+2\) where the middle point \(i+1\) is either higher than both neighbors (peak shape) or lower than both neighbors (valley shape).
For example, if the elevations are [1, 3, 2], then 1 < 3 > 2, so it is a zigzag. Also, for [4, 1, 5], 4 > 1 < 5, so this is also a zigzag.
A straightforward approach is to naively check the condition for all consecutive triplets. Since the constraint is \(N \leq 2 \times 10^5\), using a triple loop would exceed the time limit, but in this case, we can determine the result in constant time for each \(i\), so the overall processing is \(O(N)\).
Therefore, a brute-force search is sufficiently fast, and no special tricks are needed.
Algorithm
- Receive the list of elevations \(R\) as input.
- For each \(i\) (\(0 \leq i \leq N - 3\)), determine whether the three consecutive points \(R[i], R[i+1], R[i+2]\) form a zigzag:
- “Peak shape”: \(R[i] < R[i+1] > R[i+2]\)
- “Valley shape”: \(R[i] > R[i+1] < R[i+2]\)
- Increment the counter each time the condition is satisfied.
- Output the final count.
Complexity
- Time complexity: \(O(N)\)
- Space complexity: \(O(N)\) (for the input array)
Implementation Notes
Be careful with index ranges (since we access up to
i+2,iranges from0toN-3)Make sure not to mix up the direction of the inequality signs
Source Code
N = int(input())
R = list(map(int, input().split()))
count = 0
for i in range(N - 2):
if (R[i] < R[i + 1] and R[i + 1] > R[i + 2]) or (R[i] > R[i + 1] and R[i + 1] < R[i + 2]):
count += 1
print(count)
This editorial was generated by qwen3-coder-480b.
posted:
last update: