So far I haven't found any algorithm that solves this task: "An element is
considered as a peak if and only if (A[i]>A[i+1])&&(A[i]>A[i-1])
, not
taking into account edges of the array(1D)."
I know that the common approach for this problem is using "Divide & Conquer" but that's in case of taking into consideration the edges as "peaks".
The O(..) complexity I need to get for this exercise is O(log(n)).
By the image above it is clear to me why it is O(log(n)), but without the edges complexity changes to O(n), because in the lower picture I run recursive function on each side of the middle element, which makes it run in O(n) (worst case scenario in which the element is near the edge). In this case, why not to use a simple binary search like this:
public static int GetPeak(int[]A)
{
if(A.length<=2)//doesn't apply for peak definition
{
return -1;
}
else {
int Element=Integer.MAX_VALUE;//The element which is determined as peak
// First and Second elements can't be hills
for(int i=1;i<A.length-1;i++)
{
if(A[i]>A[i+1]&&A[i]>A[i-1])
{
Element=A[i];
break;
}
else
{
Element=-1;
}
}
return Element;
}
The common algorithm is written here: http://courses.csail.mit.edu/6.006/spring11/lectures/lec02.pdf, but as I said before it doesn't apply for the terms of this exercise.
Return only one peak, else return -1.
Also, my apologies if the post is worded incorrectly due to the language barrier (I am not a native English speaker).