Amazon Interview Question
Software Engineer / DevelopersCountry: India
Interview Type: Phone Interview
Its like increasing slope and then decreasing slope. We have to find the highest point.
That highest point cud be found out by using binary search, and check if
a[mid-1] a[mid] a[mid+1] is in increasing or decreasing order.
if increasing , move to right half
if decreasing, move to left half
Stopping criteria: a[mid-1] < a[mid] > a[mid+1]
I presume k is not known, and that is an important piece of info which you ought to provide.
k+1 is the maximum element, so if they give k, then finding the maximum element is trivial.
This is a variation of - If a sorted array has been rotated (circularly) then find the maximum element.
(1 2 3 4 5) rotated to (4 5 1 2 3)
int FindMax(int A[], int size)
{
return FindMaxRec(A, 0, size - 1);
}
int FindMaxRec(int A[], int start, int end)
{
if (start == end)
{
return A[start];
}
int mid = (start + end) / 2;
if (A[mid - 1] < A[mid] && A[mid + 1] < A[mid]) return A[mid];
if (A[mid - 1] < A[mid]) return FindMaxRec(A, mid + 1, end);
return FindMaxRec(A, start, mid - 1);
}
find first case while scanning array where you find an element is > next element. i.e. go on comparing the adjacent array elements. the first case where you find element (i) > element (i+1)stop here. ith element is the maximum. comments welcome!
Acc. to this code we don't need the value of k, since it is sorted in ascending order till k and descending order (k+1) onwards, we can get the answer with the following code.
Am I missing anything ?
int max(int[] num)
{
int i = 0;
while (i < num.Length)
{
while (num[i] < num[i + 1])
i++;
break;
}
return num[i];
}
1. pick the middle and check
a. A[mid-1]<A[mid]<A[mid+1] if true, this means the transition point is between mid and the right
b. A[mid-1]>A[mid]>A[mid+1] if true, this means the transition point is between mid and the left
also check if
c. A[mid-1]<A[mid] && A[mid]> A[mid+1] this means the mid is the transition point.
recursively pick the side that contains the transition point.
- GeeBee September 10, 2011