#K1016. Sawtooth Tree Pattern
Sawtooth Tree Pattern
Sawtooth Tree Pattern
You are given several test cases. In each test case, you are provided with the number of trees and a sequence of their heights. Your task is to determine whether the sequence can form a sawtooth (zigzag) pattern without rearranging the trees. A sequence is considered to form a sawtooth pattern if, for every consecutive triple of trees, the middle tree is either strictly taller than both of its neighbors or strictly shorter than both. The pattern can start with either an increase or a decrease.
Note: If there is only one tree, a sawtooth pattern is not possible. For two trees, since there is no triplet to check, consider the pattern valid if the two trees are distinct or simply follow the implicit pattern.
Formally, given a sequence of heights \( h_1, h_2, \dots, h_n \) (with \( n \geq 1 \)), the sequence is said to be sawtooth if either for every \( i \) with \( 2 \leq i \leq n-1 \) it holds that \[ h_{i-1} h_{i+1} \quad (\text{for one choice of starting direction}) \] or \[ h_{i-1} > h_i < h_{i+1} \quad (\text{for the alternate starting direction}). \]
Determine for each test case if the given tree sequence can form a sawtooth pattern. Output "YES" if it can, or "NO" otherwise.
inputFormat
The input is given from standard input in the following format:
T n1 h11 h12 ... h1n1 n2 h21 h22 ... h2n2 ... nT hT1 hT2 ... hTnT
Here, T denotes the number of test cases. For each test case, the first line contains an integer n representing the number of trees, followed by a line with n space-separated integers representing the tree heights.
outputFormat
For each test case, output a single line with either "YES" or "NO" indicating whether a sawtooth pattern is possible.
## sample4
5
3 1 4 1 5
4
1 2 3 4
3
10 20 10
3
5 5 5
YES
NO
YES
NO
</p>