Divide and conquer algorithm applied in finding a peak in an array.

前端 未结 1 1861
予麋鹿
予麋鹿 2020-12-11 19:14

For an array a: a1, a2, … ak, … an, ak is a peak if and only if ak-1 ≤ ak

相关标签:
1条回答
  • 2020-12-11 20:03

    The algorithm is correct, although it requires a bit of calculus to prove. First case is trivial → peak. Second case is a "half peak", meaning that it has the down slope, but not up.

    We have 2 possibilities here:

    • The function is monotonically decreasing till amid → a1 ≥ a2 is the peak.
    • The function is not monotonically decreasing till amid → There is a 1≥k≥mid, for which ak ≥ ak-1. Let's choose the largest k for which this statement is true → ak+1 < ak ≥ ak-1 → and that's the peak.

    Similar argument can be applied for the third case with the opposite "half peak".

    0 讨论(0)
提交回复
热议问题