How to pre-process an integer array to find the average value of any subarray in O (1)?

This problem rephrases the question. Since this original problem seems to me too complicated, I'm trying to solve a simpler one: how to process an integer array to find the average value of any submatrix in constant time. Obviously, we can process all subarrays in O(n^2). Are there any better solutions?

+3
source share
2 answers

For the 1st case: calculate the total amounts of the array, i.e. e. the given array a, define bon

b[0] = a[0];
for (int i = 1; i < n; ++i)
    b[i] = b[i - 1] + a[i];

, , , , . , i+1 j, do

average = (b[j] - b[i]) / (double)(j - i);

, .

+13

( ), , , . N + 1, N +1, , N , . , - , ( ).

: " "; , N , N, , N + 1, N + 1 . S, N, S, S N:

avg(S) = sum(S) / count(S)
S' = S + {X}
avg(S') = sum(S') / count(S')
        = (sum(S) + X) / count(S')
        = ((avg(S) * N) + X) / count(S') //QED

:. . , biggie. , . , , ( , ) , 1.

... .

+1

Source: https://habr.com/ru/post/1796319/


All Articles