A - 山脈の最高峰 / The Highest Peak of the Mountain Range 解説 by admin
GPT 5.2 HighOverview
Determine whether there exists a mountain whose elevation is strictly the unique maximum among all mountains. If such a mountain exists, output its elevation; otherwise, output \(0\).
Analysis
A “standalone peak” is a mountain whose elevation is higher than all other mountains. In other words:
- If the maximum value appears exactly once, the mountain with that maximum value is the standalone peak.
- If the maximum value appears two or more times, no mountain can satisfy “strictly higher than all others (\(>\))”, so no standalone peak exists.
For example, if the elevations are \([3, 7, 5]\), the maximum value \(7\) appears only once, so the answer is \(7\). On the other hand, if the elevations are \([3, 7, 7, 5]\), the maximum value \(7\) appears multiple times, and neither \(7\) is greater than the other \(7\), so no standalone peak exists and the answer is \(0\).
A naive approach of “comparing each mountain \(i\) against all others \(j\)” would be \(O(N^2)\), which is far too slow for \(N \le 10^6\). Since all we need is “the maximum value” and “how many times it appears,” we can solve this in \(O(N)\) with a single pass through the array.
Algorithm
- Let the variable
mxbe “the maximum elevation seen so far” andcntbe “the number of occurrences of the maximum elevation.” - Read each \(A_i\) in order:
- If \(A_i > mx\), set
mx = A_iandcnt = 1(the maximum has been updated, so reset the count). - If \(A_i == mx\), set
cnt += 1(one more occurrence of the maximum).
- If \(A_i > mx\), set
- At the end, if
cnt == 1, the answer ismx; otherwise, output \(0\).
Complexity
- Time complexity: \(O(N)\)
- Space complexity: \(O(1)\) (constant space if we don’t store the entire input. *Note: the implementation uses buffered input reading for speed.)
Implementation Notes
Since \(N\) can be as large as \(10^6\), in Python it is more reliable and faster to read all input at once with
sys.stdin.buffer.read()and parse the integers, rather than callinginput()repeatedly.Since only “the maximum value” and “the count of the maximum value” are needed for the determination, we can process elements sequentially without storing the array (which also saves memory).
The condition of outputting the maximum only when
cnt == 1corresponds to the “strict maximum (\(>\))” requirement.Source Code
import sys
def main():
data = sys.stdin.buffer.read()
l = len(data)
i = 0
def next_int():
nonlocal i
while i < l and data[i] <= 32:
i += 1
num = 0
while i < l and data[i] > 32:
num = num * 10 + (data[i] - 48)
i += 1
return num
n = next_int()
mx = -1
cnt = 0
for _ in range(n):
a = next_int()
if a > mx:
mx = a
cnt = 1
elif a == mx:
cnt += 1
sys.stdout.write(str(mx if cnt == 1 else 0))
if __name__ == "__main__":
main()
This editorial was generated by gpt-5.2-high.
投稿日時:
最終更新: