EDIT: There seems to be a very simple O (n) solution.
To solve the problem, you can use two algorithms:
Binary-search, Stack, O (n * log (n))
Let's take a few j and consider all valid subarrays ending with an element in the jth position. The answer will be i such that a [i]> a [j] and I <J . Iterating over all such i will give us complexity O (n 2 ) .
There is one simple idea to keep in mind in order to improve complexity. If we have i 1 and a [i 1 ] , we will never consider another i 2 as the starting point of a valid subarray when i 1 <i 2 and a [i 1 ]> a [i 2 ] , because i 1 gives best result. Saves such pairs (a [i], i) in the data structure d .
At any moment in time, d will look like (a [i 0 ], i 0 ), (a [i 1 ], i 1 ) ... (a [i n ], i n ) . Both i p and a [i p ] increase from left to right.
When we consider the next j as the end of a valid subarray, we can search for the current best answer in d . All i -s in d are below the current j . We should look for the left pair (a [i], i) , where a [i]> a [j] gets j - i + 1 as the current answer. Since pairs are sorted, we can use binary search.
In the case of a [j] the most a [i] of d , then we have a new pair (a [j], j) is added to d .
ans <- 0 d <- [] // contains (val, idx) structures for j = 0..n-1 l <- 0, r <- len(d) - 1 while l <= r mid = (l + r) / 2 // integer division if d[mid].val > a[j] r <- mid - 1 else l <- mid + 1 if l = len(d) append (a[j], j) to d else curAns <- j - d[l].idx + 1 ans <- max(ans, curAns)
The overall complexity is O (n * log (n)) .
Segment Tree, O (n * log (n))
Take a look at the answer of Abdenaceur Lichiheb
There are no limits on the limits of a , since they can be easily sorted and then mapped to indices in a sorted array.