Create an array of pair where each pair store the value of the element of subarray and its index.
pair[i] = (A[i],i);
Sort the pair in increasing order of A[i]
and then decreasing order of i
.
Consider example A = [1,3,6,3,6,3,1,3];
pair array after sorting will be pair = [(1,6),(1,0),(3,7),(3,5),(3,3),(3,1),(6,4),(6,2)]
pair[0]
has element of index 6
. From index 6
we can have two sub-arrays [1]
and [1,3]
. So ANS = 2
;
Now take each consecutive pair one by one.
Taking pair[0]
and pair[1]
,
pair[1]
has index 0. We can have 8 sub-arrays beginning from index 0
. But two subarrays [1] and [1,3] are already counted. So to remove them, we need to compare longest common prefix of sub-array for pair[0]
and pair[1]
. So longest common prefix length for indices beginning from 0 and 6 is 2 i.e [1,3]
.
So now new distinct sub-arrays will be [1,3,6]
.. to [1,3,6,3,6,3,1,3]
i.e. 6 sub-arrays.
So new value of ANS
is 2+6 = 8;
So for pair[i]
and pair[i+1]
ANS = ANS + Number of sub-arrays beginning from pair[i+1] - Length of longest common prefix
.
The sorting part takes O(n logn).
Iterating each consecutive pair is O(n) and for each iteration find longest common prefix takes O(n) making whole iteration part O(n^2). Its the best I could get.
You can see that we dont need pair for this. The first value of pair, value of element was not required. I used this for better understanding. You can always skip that.