简体   繁体   中英

Which is the best algorithm to find sum of all subarray?

for example if

a[3]={1,2,3}
  1,2,3,1+2,2+3,1+2+3 

so my program should print
1
2
3
3
5
8

I know there exits a formula for calculating the total sum.
But what i want is efficient method to calculate individual sums.

A seg tree advisable?

Assuming that by subarray you mean what some authors conventionally call subarray being a contiguous slice of an array, you are looking for Kadane's algorithm .

It works by incrementally finding the biggest subarray. At any given point of the search, the maximum subarray on that index is either the empty array (sum == zero) or consists of one more element than the maximum subarray that ended at the previous position. You keep track of what is the best you've ever found so you can compare subarrays with the best so far and return the actual best solution.

It may also be extended to multiple dimensions.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM