#P6510. Longest Valid Cow Lineup
Longest Valid Cow Lineup
Longest Valid Cow Lineup
Cows are lined up in a straight line under the guidance of Big Bear Mom. Not all cows have the same height. Now, the cows are curious: if we choose a contiguous segment of cows such that the leftmost cow, A, is the shortest and the rightmost cow, B, is the tallest (B is strictly taller than A), and if there are any cows between them, none of these intermediate cows have a height equal to either A or B, what is the maximum number of cows that such a segment can contain?
In other words, given a sequence of cow heights, find a contiguous subarray from index i to j (i < j) satisfying:
- The leftmost cow has height \(A = h[i]\) which is the minimum in the subarray.
- The rightmost cow has height \(B = h[j]\) which is the maximum in the subarray, and \(B > A\).
- Every cow between them (if any) has height strictly between \(A\) and \(B\) (i.e. \(A < h[k] < B\) for all i < k < j).
Your task is to output the maximum length of such a segment. Note that the answer can be 0 (if no valid segment exists) or at least 2 (it will never be 1).
inputFormat
The input consists of two lines. The first line contains an integer n representing the number of cows. The second line contains n space-separated integers, which are the heights of the cows from left to right.
outputFormat
Output a single integer: the maximum number of cows in a contiguous segment that satisfies the conditions. If no such segment exists, output 0.
sample
5
2 3 4 5 6
5