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