Leetcode accepted answer
Condition - (array is sorted, it is rotated) -
Searching for a max element in sorted rotated array in a long length array is little bit easy but we have to consider the edge cases which are the reason why maximum code answers fail at end.
Approach is similar to binary search but edge cases are different
Case 1: when array is of size 2. we can directly return max or min element from the array.
Case 2: When we return our start index, we should always double check if it is greater than the start+1 element as when we return start index we usually increase it by size one and it returns the element which is not the greatest.
Code for this:
public static int findMax(int[] nums) {
// binary search
int start = 0;
int end = nums.length - 1;
// if array length is 2 then directly compare and return max element
if(nums.length == 2){
return nums[0] > nums[1] ? 0 : 1;
}
while (start < end) {
// finding mid element
int mid = start + (end - start) / 2;
// checking if mid-element is greater than start
// then start can become mid
if (nums[start] < nums[mid]) {
start = mid;
}
// checking if mid-element is smaller than start
// then it can be ignored and end can become mid-1
else if (nums[start] > nums[mid]) {
end = mid - 1;
}
// now checking the edge case
// we have start element which is neither smaller or greater than mid
// element
// that means start index = mid-index
// so we can increase start index by 1 if current start index is smaller
// that start +1
// else the current start index is the max element
else {
if(nums[start]<=nums[start+1]) {
start = start + 1;
}
else {
return nums[start];
}
}
}
return nums[start];
}
#binarySearch #rotatedArray #sortedArray #array