-
Notifications
You must be signed in to change notification settings - Fork 86
/
Copy pathPattern132.java
53 lines (49 loc) · 1.74 KB
/
Pattern132.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
/*
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.
Test Case I:
Input: nums = [1,2,3,4]
Output: false
Explanation: There is no 132 pattern in the sequence.
Test Case II:
Input: nums = [3,1,4,2]
Output: true
Explanation: There is a 132 pattern in the sequence: [1, 4, 2].
*/
import java.util.*;
public class Pattern132 {
private static boolean find132pattern(int[] nums) {
int n = nums.length;
if (n < 3)
return false;
Deque<Integer> decreasingStack = new ArrayDeque<>(n);
int maxThirdElement = Integer.MIN_VALUE;
for (int i = n - 1; i >= 0; i--) {
int currentNumber = nums[i];
if (currentNumber < maxThirdElement)
return true;
while (!decreasingStack.isEmpty() && decreasingStack.peek() < currentNumber) {
maxThirdElement = decreasingStack.pop();
}
decreasingStack.push(currentNumber);
}
return false;
}
public static void main(String[] args){
Scanner sc = new Scanner(System.in);
int n;
System.out.println("Enter the size of the array: ");
n = sc.nextInt();
int[] nums = new int[n];
System.out.println("Enter the elements of the array: ");
for(int i=0; i<n; i++){
nums[i] = sc.nextInt();
}
boolean result = find132pattern(nums);
if(result){
System.out.println("The 132 pattern exixts in an Array");
}else{
System.out.println("The 132 pattern does not exixts in an Array");
}
}
}