1

I want to find out all the sum of continuous sub-array of length K for a given array of Length n given that k < n. For example, let the given array be arr[6]={1,2,3,4,5,6} and k=3,then answer is (6,9,12,15). It can be obtained as :

(1+2+3)=6,
(2+3+4)=9,
(3+4+5)=12,
(4+5+6)=15.

I have tried this using sliding window of length k,but its time complexity is O(n).Is any solution which takes even less time such as O(log n).

Enigma
  • 179
  • 2
  • 12

2 Answers2

7

Unless you know certain specific properties of the array (e.g. the ordering of the elements, the range of the elements included in the array, etc.) then you would need to check each individual value, resulting in an O(n) complexity.

If, for instance, you knew that the sum of the values in the array were T (perhaps because you knew T itself or were given the range) then you could consider that all the elements except the first and last (K-1) elements would be included in K different sums. This would mean a sum of T.K minus some amount, and you could reduce the values of the first and last K values appropriate amount of times, resulting in an algorithm of complexity O(K).

But note that, in order to achieve a strategy similar to this, you would have to know some other specific information regarding the values in the array, may that be their range or their sum.

ilim
  • 4,477
  • 7
  • 27
  • 46
  • 1
    If i just want to find out maximum value from the obtained answer? – Enigma Feb 08 '17 at 11:10
  • @Enigma max value in the array, or the max sum among the consecutive sub-array sums? Actually, scratch what I just asked, since in both case you would again need to have extra information to be able to avoid checking each and every value in the array, which means that you need `O(n)` time if you do not have any extra information regarding the array or the values included in it. – ilim Feb 08 '17 at 11:12
  • 1
    Max value of sum. – Enigma Feb 08 '17 at 11:18
  • 1
    @Enigma [Maximum sum continuous sub-array](http://www.geeksforgeeks.org/largest-sum-contiguous-subarray/) is a well-studied problem, and you may consider using a special version of that to find out what you are asking. Still, without some extra information (i.e. for *any* generic array) the known efficient solution for that problem has the complexity of `O(n)`. As I repetitively put, **you need to have some extra information** avoid looking into each element of the array and **to achieve a better complexity**. – ilim Feb 08 '17 at 11:22
1

You can use Segment tree data structure, though building of it will take O(n log n), but than you can find sum of any interval in O( log n ), and modify each element of array in O( log n ) https://en.wikipedia.org/wiki/Segment_tree

oybek
  • 630
  • 4
  • 14