forked from akshitagit/JavaScript
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathpeakElement.cpp
More file actions
129 lines (104 loc) · 2.95 KB
/
peakElement.cpp
File metadata and controls
129 lines (104 loc) · 2.95 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
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
/**
* Problem link: https://practice.geeksforgeeks.org/problems/peak-element/1
*
* Problem statement:
*
* An element is called peakElementIndex peak element if its value is not smaller than the value of its adjacent elements(if they exists).
* Given an array arr[] of size N, find the index of any one of its peak elements.
* Note: The generated output will always be 1 if the index that you return is correct. Otherwise output will be 0.
*
* Expected Time Complexity: O(log N)
* Expected Auxiliary Space: O(1)
*/
#include <bits/stdc++.h>
using namespace std;
class Solution {
public:
int getPeakElementIndex(int arr[], int n) {
// Get the peak element
int res = modifiedBinarySearch(arr, 0, n-1);
if (n == 1) {
return 0;
} else if (n == 2) {
if (arr[0] >= arr[1]) {
return 0;
} else {
return 1;
}
}
return res;
}
private:
int modifiedBinarySearch(int arr[], int l, int r) {
if (r >= l) {
int mid = l + (r - l) / 2;
// If the element is present at the middle itself
if (mid == r) {
return r;
}
if (mid == 0) {
return 0;
}
if (arr[mid] >= arr[mid-1] && arr[mid] >= arr[mid+1]) {
return mid;
}
// If element is smaller than mid, then it can only be present in left subarray
if (arr[mid+1] > arr[mid]) {
return modifiedBinarySearch(arr, mid + 1, r);
}
// Else the element can only be present in right subarray
return modifiedBinarySearch(arr, l, mid - 1);
}
return 0;
}
};
/**
* Driver code starts here
*/
int main() {
int t;
cin >> t;
while (t--) {
int n;
cin >> n;
int input[n];
for (int i = 0; i < n; i++) {
cin >> input[i];
}
bool output = 0;
Solution sol;
int peakElementIndex = sol.getPeakElementIndex(input, n);
if (peakElementIndex < 0 && peakElementIndex >= n)
cout << 0 << endl;
else {
if (n == 1 && peakElementIndex == 0)
output = 1;
else if (peakElementIndex == 0 && input[0] >= input[1])
output = 1;
else if (peakElementIndex == n-1 and input[n-1] >= input[n-2])
output = 1;
else if (input[peakElementIndex] >= input[peakElementIndex + 1] && input[peakElementIndex] >= input[peakElementIndex - 1])
output=1;
else
output=0;
cout << output << endl;
}
}
return 0;
}
/**
* Driver code ends here
*/
/**
* Sample test cases
*
* 4
* 3
* 1 2 3
* 13
* 9 14 10 10 1 2 1 7 10 10 14 19 9
* 1
* 2
* 2
* 2 3
*/