#C7563. Count Buildings Visible from Both Ends
Count Buildings Visible from Both Ends
Count Buildings Visible from Both Ends
You are given a sequence of building heights. A building is said to be visible from the left end if it is strictly taller than all the buildings before it. Similarly, a building is visible from the right end if it is strictly taller than all the buildings following it. Your task is to determine the number of buildings that are visible from both the left and right ends.
Note: If the list of buildings is empty, the answer is 0. Otherwise, there is always at least one building (the tallest) visible from both ends.
The visibility condition can be summarized mathematically as follows. Let \(a_1, a_2, \dots, a_n\) be the heights. Define the left-visibility set as:
[ L = { a_i \mid a_i > \max_{1 \leq j < i} a_j } ]
Similarly, define the right-visibility set as:
[ R = { a_i \mid a_i > \max_{i < j \leq n} a_j } ]
You are required to output \(|L \cap R|\), the number of buildings visible from both sides.
inputFormat
The first line of input contains a single integer \(n\) (\(n \ge 0\)) representing the number of buildings. If \(n > 0\), the second line contains \(n\) space-separated integers representing the heights of the buildings.
For example:
6 4 2 3 1 5 3
outputFormat
Output a single integer which is the number of buildings that are visible from both the left and the right ends.
## sample6
4 2 3 1 5 3
1
</p>