Reputation: 139
I have an array which has an order like
increasing, decreasing, increasing, decreasing.
I want to find out what are two local maximum elements at the end of increasing behaviors. I know i can find them O(n) time, i wonder whether it is possible to find it in O(log n) time or better than O(n) time.
Upvotes: 1
Views: 763
Reputation: 98
If you don't know that your data follows that specific pattern - increase then decrease then increase then decrease - then the best you can do is O(n), because you're going to have to examine every single item in the array to determine which the two highest points are.
If you know that it definitely does follow that pattern, then my best guess is an adaptation of binary search, which goes roughly:
Without doing the maths, my off-the-top-of-my-head guess is that this algorithm is O(2log(n)) at best, O(n) at worst. It'll certainly be pretty rare that it takes you as long as searching the entire data set, and I think you'd need a trivially small data set to take longer than the naive search.
Upvotes: 2