0

So I came up with a question that I've looked and searched but with no answer found... What's the best (and by saying the best, I mean the fastest) way to get the maximum contigous subsequence sum of x elements?

Imagine that I've: A[] = {2, 4, 1, 10, 40, 50, 22, 1, 24, 12, 40, 11, ...}. And then I ask:

"What is the maximum contigous subsequence on array A with 3 elements?"

Please imagine this in a array with more than 100000 elements... Can someone help me?

Thank you for your time and you help!

1 Answers1

0

I Googled it and found this:

Using Divide and Conquer approach, we can find the maximum subarray sum in O(nLogn) time. Following is the Divide and Conquer algorithm.

The Kadane’s Algorithm for this problem takes O(n) time. Therefore the Kadane’s algorithm is better than the Divide and Conquer approach

See the code:

Initialize:
    max_so_far = 0
    max_ending_here = 0

Loop for each element of the array
  (a) max_ending_here = max_ending_here + a[i]
  (b) if(max_ending_here < 0)
            max_ending_here = 0
  (c) if(max_so_far < max_ending_here)
            max_so_far = max_ending_here
return max_so_far
Community
  • 1
  • 1
Josh Beam
  • 19,292
  • 3
  • 45
  • 68
  • This is not really what I'm looking, because I need the maximum sum grouped by X elements... Imagine in my example above, the maximum sum is all the elements, since they are all positive, but I want the maximum sum grouped by 3 elements... So: it would be 40 50 22. – Fábio Colaço Aug 08 '15 at 12:20