Find all the amounts in O(n^2) and add them to the hash table:
for l in [0, n) cur_sum = 0 for r in [l, n) cur_sum += a[r] hash_table.add(cur_sum)
After that, we need to do the same for the second array and check if at least one sum occurs in the hash table.
This is much better than the naive O(n^3) solution.
You can also solve this problem in O(H log H) time, where H is the sum of the heights of the boxes if all the heights are integers, but this is only useful if the total height is limited.
The solution O(H log H) as follows:
We can quickly find all subarahms. Let’s see what subarahma S . This is the difference between the two prefix sums P[r] - P[l] = S If we add H to both sides of the equation, we get P[r] + (H - P[l]) = H + S Therefore, we need to check whether there are two elements in the array P[i] and H - P[i] , respectively, which add up to the given value. Let not just check their existence, but also count the number of such pairs. No, it looks exactly like multiplying two polynomials. The coefficients of the first polynomial are the number of occurrences of a particular sum of the prefix ( C[i] = count(j: P[j] == i) ). The second polynomial, in fact, is one and the same inverse. We can multiply these two polynomials by the time O(H log H) using the fast Fourier transform (since both of them have degree H ). After that, we just need to verify that the H + i coefficient for the product is non-zero.
As soon as we find out all the sums for the first and second arrays, we need to check whether they have at least one thing in common.
kraskevich
source share