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?
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).
There is no faster solution.
Since your output size is O(n2), not algorithm can be faster.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With