Given an array of n integers nums, a 132 pattern is a subsequence of three integers nums[i], nums[j] and nums[k] such that i < j < k and nums[i] < nums[k] < nums[j].
Return true if there is a 132 pattern in nums, otherwise, return false.
Input: nums = [1,2,3,4]
Output: false
Explanation: There is no 132 pattern in the sequence.
Input: nums = [3,1,4,2]
Output: true
Explanation: There is a 132 pattern in the sequence: [1, 4, 2].
Input: nums = [-1,3,2,0]
Output: trueExplanation: There are three 132 patterns in the sequence: [-1, 3, 2], [-1, 3, 0] and [-1, 2, 0].
The brute force approach involves checking every possible triplet to see if it forms a 132 pattern. The 132 pattern means finding three indices i, j, k such that i < j < k and nums[i] < nums[k] < nums[j].
i.i, fix j and ensure j > i.j, loop over the array to find an element k, where k > j and nums[i] < nums[k] < nums[j].n is the length of the array, due to the three nested loops.To optimize, we can use a stack to maintain candidates for the second largest number (nums[j]) in the pattern 132 by iterating from the right. We will also maintain a variable nums[k] as the second number in the 132 pattern.
third to track the maximum number less than nums[j] which can be a candidate for nums[k].nums[j].nums[i], check:nums[i] is less than third, a valid 132 pattern is found.nums[j] candidates.