I recently came across this HackerRank contest problem (Coolguy and Two Subsequences). The question is to reduce the given pseudocode complexity from O(N4) to something much lesser.
//f(a, b) is a function that returns the minimum array element in interval [a, b]
array = [...] (of length n)
ans = 0
for a -> [1, n]
for b -> [a, n]
for c -> [b + 1, n]
for d -> [c, n]
ans = ans + min(f(a, b), f(c, d))
Given editorial solution achieves a complexity of O(N log N). I found the problem an interesting concept to learn. Unfortunately, I had difficulty in understanding the editorial solution which uses segment trees to store sub solutions in a given range and finally merge it give the final solution. Specifically I did not understand the significance of each term in the segment tree.
I understand that the question has alternative solutions too. Can someone please explain an approach to do the question. Code is not required but you can add it if it helps you in explaining the solution better.