Finding sub-array sum in an integer array

前端 未结 2 1201
無奈伤痛
無奈伤痛 2021-01-31 12:53

Given an array of N positive integers. It can have n*(n+1)/2 sub-arrays including single element sub-arrays. Each sub-array has a sum S. Find S\'

相关标签:
2条回答
  • 2021-01-31 13:30

    You can look at the sub-arrays as a kind of tree. In the sense that subarray [0,3] can be divided to [0,1] and [2,3].

    So build up a tree, where nodes are defined by length of the subarray and it's staring offset in the original array, and whenever you compute a subarray, store the result in this tree.

    When computing a sub-array, you can check this tree for existing pre-computed values.

    Also, when dividing, parts of the array can be computed on different CPU cores, if that matters.

    This solution assumes that you don't need all values at once, rather ad-hoc. For the former, there could be some smarter solution.

    Also, I assume that we're talking about counts of elements in 10000's and more. Otherwise, such work is a nice excercise but has not much of a practical value.

    0 讨论(0)
  • 2021-01-31 13:38

    When S is not too large, we can count the distinct sums with one (fast) polynomial multiplication. When S is larger, N is hopefully small enough to use a quadratic algorithm.

    Let x_1, x_2, ..., x_n be the array elements. Let y_0 = 0 and y_i = x_1 + x_2 + ... + x_i. Let P(z) = z^{y_0} + z^{y_1} + ... + z^{y_n}. Compute the product of polynomials P(z) * P(z^{-1}); the coefficient of z^k with k > 0 is nonzero if and only if k is a sub-array sum, so we just have to read off the number of nonzero coefficients of positive powers. The powers of z, moreover, range from -S to S, so the multiplication takes time on the order of S log S.

    0 讨论(0)
提交回复
热议问题