Sub array that produces a given sum and product

后端 未结 4 1658
执念已碎
执念已碎 2021-01-14 13:48

Given an array of length N. How will you find the minimum length contiguous sub-array of whose sum is S and whose product is P. For eg 5 6 1 4 6 2 9 7 fo

4条回答
  •  既然无缘
    2021-01-14 14:01

    Put two indices on the array. Lets call them i and j. Initially j = 1 and i =0. If the product between i and j is less than P, increment j. If it is greater than P, increment i. If we get something equal to p, sum up the elements (instead of summing up everytime, maintain an array where S(i) is the sum of everything to the left of it. Compute sum from i to j as S(i) - S(j)) and see whether you get S. Stop when j falls out of the array length.

    This is O(n).

提交回复
热议问题