-
Notifications
You must be signed in to change notification settings - Fork 0
/
find the peak element.txt
75 lines (44 loc) · 1.23 KB
/
find the peak element.txt
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
Given an array of integers A, find and return the peak element in it. An array element is peak if it is NOT smaller than its neighbors.
For corner elements, we need to consider only one neighbor. We ensure that answer will be unique.
Problem Constraints
1 <= |A| <= 100000
1 <= A[i] <= 10^9
Input Format
The only argument given is the integer array A.
Output Format
Return the peak element.
Example Input
Input 1:
A = [1, 2, 3, 4, 5]
Input 2:
A = [5, 17, 100, 11]
Example Output
Output 1:
5
Output 2:
100
Example Explanation
Explanation 1:
5 is the peak.
Explanation 2:
100 is the peak.
...............................Algorithm.................................
If you observe an elements in the array according to your question then you will find that you
will find that you can reduce your search space.
we have only three cases :look into the code.
int sol(vector<int> &a,int start,int end){
if(start>=end){
return a[start];
}
int mid=start+(end-start)/2;
if(mid>0 and a[mid-1]>a[mid]){
return sol(a,start,mid-1);
}
if(mid<end and a[mid+1]>a[mid]){
return sol(a,mid+1,end);
}
return a[mid];
}
int Solution::solve(vector<int> &A) {
return sol(A,0,A.size()-1);
}