Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Sum of all contiguous subarrays optimisation

I am solving a problem where I have an array and for two given indices min and max, I need to find sum of all contiguous sub-arrays between them.

All I could think is of this O(n2) code

for (int i = min; i <= max; ++i)
{
    long long sum = 0;
    for (int j = i; j <= max; ++j)
    {
        sum += a[j];
        printf("%lld\n", sum);
    }
}

Can anyone please help me with optimising this code?

like image 816
vinay_Kumar Avatar asked Dec 15 '25 07:12

vinay_Kumar


2 Answers

Using dynamic programming you can achieve O(n) answer. The idea basically is to calculate prefix sums accumulated for all elements.

Let A(i) be the summation of elements from 0 to i. This can be calculated easily in O(n) by:

// let your array by Src[Max]
int A[MAX];
A[0] = Src[0];

for(int i = 1; i < MAX; i++) {
    A[i] += A[i - 1] + (i + 1) * Src[i];
}

Then for any elements i and j, you can calculate sum(i,j) = A[j] - A[i] (adjust for boundaries depending on input requirements).

like image 132
aybassiouny Avatar answered Dec 16 '25 21:12

aybassiouny


There is no faster solution.

Since your output size is O(n2), not algorithm can be faster.

like image 24
Hans Klünder Avatar answered Dec 16 '25 19:12

Hans Klünder



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!