Given an array of integers, find the local minima. An element A[i] is defined as a local minimum if A[i-1] > A[i] and A[i] < A[i+1] where i = 1...n-2. In case of boundary elements, the number has to be just smaller than its adjacent number.
I know if there is only one local minimum, then we can solve with modified binary search. But if it is known that there exist multiple local minima in the array, can it be solved in O(log n)
time?
Given an array of integers, find the local minima. An element A[i] is defined as a local minimum if A[i-1] > A[i] and A[i] < A[i+1] where i = 1...n-2. In case of boundary elements, the number has to be just smaller than its adjacent number.
Approach: The idea is to iterate over the given array arr[] and check if each element of the array is smallest or greatest among their adjacent element. If it is smallest then it is local minima and if it is greatest then it is local maxima.
To find the local minimum of any graph, you must first take the derivative of the graph equation, set it equal to zero and solve for . To take the derivative of this equation, we must use the power rule, . We also must remember that the derivative of a constant is 0.
If the array elements are not guaranteed to be distinct, then it's not possible to do this in O(log n) time. The reason for this is the following: suppose that you have an array where all n > 1 values are the same. In this case, none of the elements can be local minima, because no element is less than its neighbors. However, in order to determine that all values are the same, you will have to look at all the array elements, which takes O(n) time. If you use less than O(n) time, you can't necessarily look at all the array elements.
If, on the other hand, the array elements are guaranteed to be distinct, you can solve this in O(log n) time using the following observations:
Consequently, you can build up the following recursive algorithm:
Notice that this has the recurrence relation
T(1) ≤ 1
T(2) ≤ 1
T(n) ≤ T(n / 2) + 1
Using the Master Theorem, you can show that this algorithm runs in time O(log n), as required.
Hope this helps!
Please also notice that this algorithm only works if edges of the array count as local minima if they are smaller than the adjacent element.
The number of local minima can be n/2
; you can't enumerate them all in O(log n)
time.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With