#K37182. Trees Visible from Both Sides
Trees Visible from Both Sides
Trees Visible from Both Sides
Given t test cases, each test case consists of an array of tree heights. A tree is considered visible from the left if it is strictly taller than all trees to its left, and visible from the right if it is strictly taller than all trees to its right. A tree is counted as visible from both sides if it appears in both the left-visible and right-visible sequences.
More formally, let the height array be \( H = [h_1, h_2, \dots, h_n] \). A tree at index \( i \) is visible from the left if \[ h_i > \max\{h_1, h_2, \dots, h_{i-1}\} \quad (\text{with } \max\{\}=-\infty) \] and visible from the right if \[ h_i > \max\{h_{i+1}, h_{i+2}, \dots, h_n\} \quad (\text{with } \max\{\}=-\infty). \]
Your task is to determine the number of trees that are visible from both the left and the right for each test case.
inputFormat
The input is read from STDIN and has the following format:
T n h1 h2 ... hn [note: this pattern repeats T times]
Where:
T
is the number of test cases.- For each test case, an integer
n
denotes the number of trees. - The next line contains
n
integers separated by spaces, representing the heights of the trees.
outputFormat
For each test case, output a single line containing a single integer: the number of trees that are visible from both sides (left and right).
The output should be written to STDOUT.
## sample3
5
4 2 3 6 1
6
1 2 2 3 4 2
3
5 4 3
1
2
1
</p>