TITLE: What is the most efficient way to find the most separated pair in a finite sequence such that the first is greater than the second?
QUESTION [5 upvotes]: Given some finite sequence $a_n$ for $n \in \{1..N\}$, is there a more efficient method to solve (P1) than the O($N^2$) brute force method?
($P1$) maximise $n_2-n_1$ such that $a_{n_1}>a_{n_2}$

REPLY [4 votes]: This is $O(N)$.
If $a_n$ is greater than all the elements before it, call it a peak; and if $a_n$ is less than all elements after it, call it a trough.
Then if $(a_i,a_j)$ is a maximally separated pair satisfying $a_i>a_j$, we know that $a_i$ must be a peak (otherwise there would be an earlier element $a_k$ such that $a_k>a_j$); and similarly, $a_j$ must be a trough.
So here is the algorithm:

Scan forwards through the sequence, marking all peaks ($N$ steps).
Scan backwards through the sequence, marking all troughs ($N$ steps).
Set $p = 1$ (this is the peak index). Note that $a_1$ is a peak by definition.
Set $t$ (the trough index) to be the index of the last trough such that $a_t < a_p$.
Now $t-p$ is a candidate for the maximal separation; if it is the best yet, remember it.
If we have scanned all peaks, we are done. Otherwise, set $p$ to be the index of the next peak and go to Step 4.

Note that we can start the scan in Step 4 from the value of $t$ in the previous iteration, so the total number of operations used by that step in the whole algorithm is $O(N)$.
Edited to add: In fact we can omit Step 1, and just scan for the next peak in Step 6. (We can't omit Step 2, because scanning for troughs has to be done backwards.)