-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathSorted_Subsequence_of_size_3.cpp
More file actions
87 lines (72 loc) · 2.06 KB
/
Sorted_Subsequence_of_size_3.cpp
File metadata and controls
87 lines (72 loc) · 2.06 KB
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
79
80
81
82
83
84
85
86
87
//{ Driver Code Starts
#include <bits/stdc++.h>
using namespace std;
bool isSubSequence(vector<int> &v1, vector<int> &v2) {
int m = v2.size();
int n = v1.size();
int j = 0; // For index of v2
// Traverse v1 and v2
for (int i = 0; i < n && j < m; i++) {
if (v1[i] == v2[j]) {
j++;
}
}
return (j == m);
}
// } Driver Code Ends
// Function to find three numbers in the given array
// such that arr[smaller[i]] < arr[i] < arr[greater[i]]
class Solution {
public:
vector<int> find3Numbers(vector<int> &arr) {
int n = arr.size();
if(n < 3) return {};
vector<int> smaller(n, 1e9);
vector<int> greater(n, 0);
smaller[0] = arr[0];
greater[n-1] = arr[n-1];
for(int i = 1; i < n; i++)
smaller[i] = min(smaller[i-1], arr[i]);
for(int i = n-2; i >= 0; i--)
greater[i] = max(greater[i+1], arr[i]);
for(int i = 0; i < n; i++)
{
if(arr[i] > smaller[i] && arr[i] < greater[i])
return {smaller[i], arr[i], greater[i]};
}
return {};
}
};
//{ Driver Code Starts.
// Driver program to test above function
int main() {
int t;
cin >> t;
cin.ignore();
while (t--) {
vector<int> arr;
string input;
getline(cin, input);
stringstream ss(input);
int number;
while (ss >> number) {
arr.push_back(number);
}
int n = arr.size();
Solution obj;
auto res = obj.find3Numbers(arr);
// wrong format output
if (!res.empty() and res.size() != 3) {
cout << -1 << "\n";
}
if (res.empty()) {
cout << 0 << "\n";
} else if ((res[0] < res[1] and res[1] < res[2]) and isSubSequence(arr, res)) {
cout << 1 << "\n";
} else {
cout << -1 << "\n";
}
}
return 0;
}
// } Driver Code Ends