Problem 591
132 Pattern
Medium · 20 pts · Array, Monotonic Stack
Problem
A 132 pattern is a choice of three indices i < j < k with A[i] < A[k] < A[j]: the first value is the smallest, the middle one the largest, and the last one in between. Decide whether the array contains a 132 pattern. Scan from the right with a decreasing stack; whenever a larger value pops smaller ones, the largest popped value becomes the best candidate for A[k], and a later value below that candidate completes the pattern.
Input
The first line contains an integer N, the size of the array. The second line contains N space-separated integers A[0], A[1], ..., A[N-1].
Output
Print YES if the array contains a 132 pattern, otherwise NO.
Constraints
1 <= N <= 100000; -10^9 <= A[i] <= 10^9
Example input
4 3 1 4 2
Example output
YES
Explanation
In 3 1 4 2, take A[1] = 1, A[2] = 4 and A[3] = 2. Since 1 < 2 < 4, this is a 132 pattern and the answer is YES.