Suppose an array of length n sorted in ascending order is rotated between 1 and n times.
For example, the array nums = [0,1,2,4,5,6,7] might become:
Notice that rotating an array [a[0], a[1], a[2], ..., a[n-1]] 1 time results in the array [a[n-1], a[0], a[1], a[2], ..., a[n-2]].
Given the sorted rotated array nums of unique elements, return the maximum element of this array.
You must write an algorithm that runs in O(log n) time.
Example 1:
Example 2:
Example 3:
Since we need a time complexity of O(log n), we will use binary search.
The key idea is to compare the middle element with the rightmost element.
Steps:
public int findMax(int[] arr) {
if(arr == null || arr.length == 0)
throw new ArrayIndexOutOfBoundsException("Null / Empty array");
if(arr.length == 1 || arr[0] <= arr[arr.length - 1]) return arr[arr.length - 1];
int l = 0, r = arr.length - 1;
while(l < r) {
int mid = l + (r - l) / 2;
// check the highest element near to mid
if(mid < r && arr[mid] > arr[mid + 1]) return arr[mid];
if(mid > l && arr[mid] < arr[mid - 1]) return arr[mid - 1];
if(arr[mid] < arr[l]) r = mid - 1;
else l = mid + 1;
}
return arr[l];
}
public int findMax(int[] arr) {
if (arr == null || arr.length == 0) return -1;
if (arr.length == 1) return arr[0];
if (arr[0] < arr[arr.length - 1]) return arr[arr.length - 1];
int l = 0, r = arr.length - 1;
/*
* Modified binary search to find the maximum element in the rotated
* sorted array.
*/
while (l < r) {
int m = l + (r - l) / 2;
if (arr[m] > arr[r]) l = m + 1;
else r = m;
}
return arr[l - 1];
}