I have been studying divide-and-conquer for a while, and am now looking into the following problem:
Given a permutation P of length N, count the number of good segments. Note that a sequence A of N integers is called a permutation of length N if:
1≤ Ai ≤ N for all 1 ≤ i ≤ N, and Ai != Aj for all 1 ≤ i != j ≤ N.
A continuous segment [l, r] of a permutation P is good if the value of (Pl, Pl+1, ..., Pr) is also continuous. That is, if we collect Pl, Pl+1, ..., Pr into a new list B and sort it, then this will hold:
B1 = B2−1, B2 = B3−1, ..., Bi-1 = Bi−1, ..., B|B|−1 = B|B|−1.
For example, in the permutation [3, 2, 4, 5], there are 8 good segments:
[3], [2], [4], [5], [3,2], [4,5], [3,2,4], and [3,2,4,5]
I analysed several cases when combining two small divided arrays, but I cannot think of a strategy that can detect good segments that cross two separate arrays in O(N) time.
How can this be done?