A - 山の頂上 / Mountain Summit 解説 by admin
gpt-5.3-codexOverview
This is a problem about counting the number of points (peaks) that have a higher elevation than both their left and right neighbors. It can be solved by scanning the array once and checking whether each middle element \(A_i\) satisfies \(A_{i-1} < A_i > A_{i+1}\).
Analysis
The condition for a peak is “a point \(i\) is higher than its left neighbor and higher than its right neighbor.” In other words, whether point \(i\) is a peak can be determined by looking at only the three values \(A_{i-1}, A_i, A_{i+1}\).
The two important observations here are:
- The endpoint positions (\(i=1, N\)) have a neighbor on only one side, so they can never be peaks.
→ The range to check is only from the 2nd to the \((N-1)\)-th position (in 0-index, from
1toN-2). - The check at each point is independent, and checking once each is sufficient. → The answer can be obtained with just a single pass through the array.
For this problem, complex approaches such as “grouping mountain shapes” or “finding the maximum value per interval” are unnecessary. Since we simply check each point on the spot, the most straightforward linear scan is optimal.
Example: When \(A=[1,3,2,4,4,1]\) - \(i=2\) (value 3): \(1<3\) and \(3>2\) → peak - \(i=3\) (value 2): \(3<2\) is false → not a peak - \(i=4\) (value 4): \(2<4\) and \(4>4\) — the latter is false (equal) → not a peak - \(i=5\) (value 4): \(4<4\) is false → not a peak
Therefore the count is 1.
Algorithm
- Read \(N\) and the array \(A\) from input.
- Initialize
count = 0. - Loop
ifrom1toN-2(0-indexed). - If the condition
A[i-1] < A[i] and A[i] > A[i+1]is satisfied, incrementcount += 1. - Output
countat the end.
The provided code implements this procedure directly.
Complexity
- Time complexity: \(O(N)\) Because each point is checked at most once.
- Space complexity: \(O(1)\) (auxiliary space excluding the input array)
The only additional variables used are a constant number, such as
count.
Implementation Notes
In Python, since arrays are 0-indexed, the correct check range is
for i in range(1, N-1):.Note that the comparisons use strict inequalities (
<,>). Using>=or<=will lead to wrong answers.Since the input size can be relatively large, using
sys.stdin.readlineis recommended for safety.Source Code
import sys
def main():
input = sys.stdin.readline
N = int(input().strip())
A = list(map(int, input().split()))
count = 0
for i in range(1, N - 1):
if A[i - 1] < A[i] and A[i] > A[i + 1]:
count += 1
print(count)
if __name__ == "__main__":
main()
This editorial was generated by gpt-5.3-codex.
投稿日時:
最終更新: