Consider an array A = [5,1,7,2,3]
All contiguos subarrays = { [5], [1], [7], [2], [3], [5,1], [1,7], [7,2], [2,3],
[5,1,7], [1,7,2], [7,2,3], [5,1,7,2], [1,7,2,3], [5,1,7,2,3] }
Replace all the arrays in the above set with maximum element in it:
set will look like this: { [5], [1], [7], [2], [3], [5], [7], [7], [3],
[7], [7], [7], [7], [7], [7] }
Frequency info: [5] -> 2, [1] -> 1, [7] -> 9, [2] -> 1, [3] -> 2
My Goal is to find the above frequency info.
My Approach:
First make a list of pair (x,y). x is element in A and its index is y.
LIST : [ (5,1), (1,2), (7,3), (2,4), (3,5) ]
Sort the list in decreasing order with respect to first element.Now,
LIST : [ (7,3), (5,1), (3,5), (2,4), (1,2) ]
Algorithm:
def f( array, first_index, last_index):
->select an element from LIST starting from left which
is not marked as visited and (first_index <= element.second <=
last_index)
->calculate frequency info of element in tuple as (element.secondvalue-first_index+1) + (element.secondvalue-first_index+1)*(last_index - element.second_value)
->Mark above element as visited
->Recursively solve f( array, first_index,element.secondvalue-1 ),f( array,element.secondvalue+1,last_index)
We can easily set suitable base case.
Time complexity:O(n*n)
I have tried a lot to come with the above algorithm but unable to improve time complexity.How I can do so?Any hint,approach will be appreciated.
See Question&Answers more detail:
os