Given an array I should compute the following sum in linear time:
My most naive implementation is O(n3):
sum_ = 0
for i in range(n):
for j in range(n, i, -1):
sum_ += max(arr[i:j]) * (j-i)
I have no idea what to do. I have tried many algorithms but they were at best O(n*log(n)), but I should solve it in linear time. Also, I don't get the idea, is there a mathematical way of just looking at an array and telling the result of the above sum?
