3

So I watched a couple of videos regarding this and the divide and conquer made sense to me. But I am still not convinced as to how recursing on the side with the larger number guarantees us the solution.

Please can someone explain it Mathematically.

Shivangi Singh
  • 131
  • 1
  • 4

2 Answers2

4

To reformulate the question, there is the following problem: given an array of numbers, find an index in the array that is a local maximum, meaning the value at that index $\ge$ the values at adjacent indices.

The algorithm suggested works as follows. Perform a binary search on the array. At each iteration choose a middle element of the array; examine its neighbors; if it is a local maximum or the binary search has narrowed down to just one item, output its index; otherwise recurse on a side with a greater neighbor. Clearly this algorithm runs in $O(\log n)$.

Your question is why this algorithm works.

The first observation is that every array has a local maximum. That is because an array of length 1 has a local maximum and if every array of length $n$ has a local maximum then given an array of length $n+1$, either its first element is a local maximum or each local maximum in the sub-array starting at the second element is a local maximum of the full array.

Now suppose there are two consecutive elements of the array $a, b$ and $a < b$. Every local maximum of the sub-array starting at $b$ is a local maximum of the full array and as shown in the previous paragraph, there must be at least one. Similarly if $a > b$, every local maximum of the sub-array ending at $a$ is a local maximum of the full array and there must be at least one. The algorithm always recurses to one of those mentioned sub-arrays and therefore when it gets to a single-element sub-array, whose only element is a local maximum of itself, that element is also a local maximum of the sub-array in the previous step, which must be a local maximum of the sub-array two steps prior, etc., all the way back to the full array.

Reinstate Monica
  • 589
  • 3
  • 12
3

No, it is not possible to find the max (peak) element in an unsorted array better than $\mathcal{O}(n)$.

When you executed your algorithm $\mathcal{A}$ that has $c \log n$ compare operations, that means; $\mathcal{A}$ only compared $c \log n$ elements. The remaining are not compared by $\mathcal{A}$.

We can easily construct an adversary argument for any $\mathcal{O}(\log n)$ algorithm by just placing the peak, within the elements for $\mathcal{A}$ didn't touch.

kelalaka
  • 1,161
  • 1
  • 10
  • 19
  • The question asks for finding the local peak, not the global peak. – SOFe May 06 '19 at 11:07
  • 1
    @SOFe If you look at the original question, it was not local. The OP changed the question after the my answer, so I've kept it. – kelalaka May 06 '19 at 11:48