Frequency of each element of an array considering all contiguos subarrays

前端 未结 4 2016
别跟我提以往
别跟我提以往 2020-12-17 04:14

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],

4条回答
  •  北海茫月
    2020-12-17 05:06

    Traverse your value-to-index map from bottom to top - maintain an augmented tree of intervals. Each time an index is added, adjust the appropriate interval and calculate the total from the relevant segment:

    A = [5,1,7,2,3] => {1:1, 2:3, 3:4, 5:0, 7:2}
    
    indexes     interval     total sub-arrays with maximum exactly
    1           (1,1)        1 =>           1
    1,3         (3,3)        2 =>           1 
    1,3,4       (3,4)        3 =>           2
    1,3,4,0     (0,1)        5 =>           2
    1,3,4,0,2   (0,4)        7 => 3 + 2*3 = 9
    

    Insertion and deletion in augmented trees are of O(log n) time-complexity. Worst-case total time-complexity is O(n log n).

提交回复
热议问题