公式

A - 山脈の最高峰 / The Highest Peak of the Mountain Range 解説 by admin

Gemini 3.1 Pro (Thinking)

Overview

Given the elevations of \(N\) mountains, the problem asks us to determine whether there exists a “unique maximum” that is higher than all other mountains. If it exists, output that value; otherwise, output \(0\).

Analysis

The condition for an “independent peak” described in the problem statement is equivalent to a mountain’s elevation being higher than all other mountains, i.e., it is the strict maximum of the entire set.

A naive approach would be, for each mountain \(i\), to check whether it is higher than all other mountains \(j\). However, this method requires a double loop with a time complexity of \(O(N^2)\). Since the constraint is \(N \leq 10^6\), this would result in TLE (Time Limit Exceeded).

Instead, we shift our perspective and focus on the “overall maximum.” If the maximum value appears exactly once in the array, it is the independent peak. If it appears \(2\) or more times, there is no independent peak. This allows us to find the answer efficiently by simply scanning the array.

Algorithm

  1. Find the maximum value \(M\) in the given elevation array \(A\).
  2. Count the number of elements in array \(A\) that are equal to \(M\).
  3. If the count is exactly \(1\), then \(M\) is the unique maximum (independent peak), so output \(M\).
  4. If the count is \(2\) or more, there are multiple mountains with the same highest elevation and no independent peak exists, so output \(0\).

Complexity

  • Time complexity: \(O(N)\)
    • Finding the maximum takes \(O(N)\), and counting its occurrences takes \(O(N)\). Since we only scan the array twice, the overall complexity is \(O(N)\), which is sufficiently fast even for \(N = 10^6\).
  • Space complexity: \(O(N)\)
    • Used to store the \(N\) elevation values in a list in memory.

Implementation Notes

  • By utilizing Python’s built-in functions, finding the maximum can be written concisely as max(A), and counting elements as A.count(max_A).

  • Since \(N \leq 10^6\) and the input size is relatively large, instead of calling input() in a loop, we use sys.stdin.read().split() to read all input at once, speeding up input processing and preventing TLE.

    Source Code

import sys

def main():
    input_data = sys.stdin.read().split()
    if not input_data:
        return
    
    A = list(map(int, input_data[1:]))
    max_A = max(A)
    
    if A.count(max_A) == 1:
        print(max_A)
    else:
        print(0)

if __name__ == '__main__':
    main()

This editorial was generated by gemini-3.1-pro-thinking.

投稿日時:
最終更新: