Find local minima in an array

You are given an array Arr[1 .. n] with the special property that Arr[1] ≥ Arr[2] and Arr[n − 1] ≤ Arr[n]. We say that an element Arr[x] is a local minimum if it is less than or equal to both its neighbors. Derive an algorithm in O(log n)

For example in the array 9,6,2,14,5,7,4 – 2 is a local minima as it is smaller than its left and right number 6 and 14. Similarly 5 is another local minima as it is between 14 and 7, both larger than 5. You need to find any one of the local minima.


Solution:

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 and with the given properties, you can solve this in O(log n) time using the following observations:

  1. If there is just one array element, it’s a local minimum.
  2. If there are two array elements, check each. One must be a local minimum.
  3. Otherwise, look at the middle element of the array. If it’s a local minimum, return it. Otherwise, at least one adjacent value must be smaller than this one. Recurs in the half of the array containing that smaller element (but not the middle).
intfindLocalMinima(int[] arr, intstart,intend)
{
    intmid = (start + end) / 2;
    if(mid - 2 < 0 && mid + 1 >= arr.length)
        return-1;
    if(arr[mid - 2] > arr[mid - 1] && arr[mid - 1] < arr[mid])
        returnarr[mid - 1];
    if(arr[mid - 1] > arr[mid - 2])
        returnfindLocalMinima(arr, start, mid);
    else
        returnfindLocalMinima(arr, mid, end);
}

Complexity O(log N)


The 1D case is solved by binary search:
If a[1] < a[2], a[1] is an LM.
Otherwise, if a[n-1] > a[n], a[n] is an LM.
Otherwise, the array entries start out descending (going from a[1] to a[2]) and ends up ascending (going from a[n-1] to a[n]).  It follows that an LM must exist somewhere in between.  Examine a[n/2].  If a[n/2] > a[n/2+1], then by the same reasoning there is an LM in the upper half of the array.  Similarly, if a[n/2] < a[n/2+1] there is an LM in the lower half of the array.  Solve recursively in the appropriate half.

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值