-
Notifications
You must be signed in to change notification settings - Fork 22
/
Copy pathelement with left side smaller and right side greater
78 lines (61 loc) · 1.5 KB
/
element with left side smaller and right side greater
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
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
/*
Given an unsorted array of size N. Find the first element in array such that all of its left elements are smaller and all right elements
to it are greater than it.
Note: Left and right side elements can be equal to required element. And extreme elements cannot be required element.
Input:
The first line of input contains an integer T denoting the number of test cases. Then T test cases follow. Each test case consists of
two lines. First line of each test case contains an Integer N denoting size of array and the second line contains N space separated array
elements.
Output:
For each test case, in a new line print the required element. If no such element present in array then print -1.
Constraints:
1 <= T <= 100
3 <= N <= 106
1 <= A[i] <= 106
Example:
Input:
3
4
4 2 5 7
3
11 9 12
6
4 3 2 7 8 9
Output:
5
-1
7
Explanation:
Testcase 1 : Elements on left of 5 are smaller than 5 and on right of it are greater than 5.
*/
#include <bits/stdc++.h>
using namespace std;
int findPivot(int a[], int n)
{
int Left_max[n];
int Right_min[n];
Left_max[0]=INT_MIN;
Right_min[n-1]=INT_MAX;
for(int i=1;i<n;i++){
Left_max[i]=max(a[i-1],Left_max[i-1]);
}
for(int i=n-1; i>=0; i--)
{
Right_min[i-1] = min(Right_min[i], a[i]);
}
for(int i=1;i<n-1;i++){
if(a[i]>=Left_max[i] && a[i]<=Right_min[i]){
return a[i];
}
}
return -1;
}
int main() {
int t; cin>>t; while(t--){
int n; cin>>n;
int a[n]; for(int i=0; i<n; i++) cin>>a[i];
cout<<findPivot(a,n);
cout<<'\n';
}
return 0;
}