Given the sequence a[1], a[2], a[3] .... a[n], I must find for each a[i]element a[j]where a[j]is the first element in the sequence a[i - 1], a[i - 2], a[i - 3]....such that a[j] < a[i].
In other words, I have to find a[j]where a[j] < a[i]and 1<=j<i. But if there are several such elements, I must choose the one that is closest to a[i].
For example, in the following sequence:
2 6 5 8
I need to print 2 for 6 and 5 and 5 for 8.
I know this can easily be done in O(n^2), but is there a more efficient way to do this?
source
share