Since cases 1-3 have one peak (a value surrounded on both sides by values โโbelow itself or the edge of the array), and case 4 has two peaks at both ends of the array, this problem can be solved simply in O(log n) time for all cases:
First apply the 1D peak search algorithm to find the peak in the array.
If the peak occurs in the middle of the array (not in the first or last position), then this is case No. 3, and the peak is also maximum.
If the peak is the first or last element of the array, then this is one of the cases 1, 2 or 4, and the max array is the maximum (first, last).
Python-esque pseudo-code:
def find-peak(list): mid=len(list)/2 if (list[mid-1] > list[mid]: return find-peak(list[:mid-1]) else if (list[mid+1] > list[mid]: return find-peak(list[mid+1:]) else: return mid def find-max(list): peak = find-peak(list) if peak==0 or peak==len(list)-1: return max(list[0], list[-1]) else: return list[peak]
Patrick
source share