Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    primarykey
    data
    text
    <p>Kadane's algorithm keeps track of the maximum value of a sequence ending at the current point, and the maximum value seen so far.</p> <p>Here is a Python implementation based on <a href="http://en.wikipedia.org/wiki/Maximum_subarray_problem" rel="nofollow">the wikipedia page</a>:</p> <pre><code>def kadane(A): max_ending_here = max_so_far = 0 for x in A: max_ending_here = max([x,0,max_ending_here+x]) max_so_far = max(max_so_far,max_ending_here) return max_so_far </code></pre> <p>We can modify the algorithm to keep track of the count of such sequences by adding two variables:</p> <ul> <li><strong>count_with_max_ending_here</strong> to count the number of sequences ending at the current point with values that sum to max_ending_here</li> <li><strong>count_with_max</strong> to count the number of sequences found so far with the maximum value</li> </ul> <p>Kadane's algorithm can be straightforwardly changed to keep track of these variables while staying at O(n) complexity:</p> <pre><code>def kadane_count(A): max_ending_here = max_so_far = 0 count_with_max_ending_here = 0 # Number of nontrivial sequences that sum to max_ending_here count_with_max = 0 for i,x in enumerate(A): new_max = max_ending_here+x if new_max&gt;=0: if count_with_max_ending_here==0: # Start a nontrivial sequence here count_with_max_ending_here=1 elif max_ending_here==0: # Can choose to carry on a nontrivial sequence, or start a new one here count_with_max_ending_here += 1 max_ending_here = new_max else: count_with_max_ending_here = 0 max_ending_here = 0 if max_ending_here &gt; max_so_far: count_with_max = count_with_max_ending_here max_so_far = max_ending_here elif max_ending_here == max_so_far: count_with_max += count_with_max_ending_here return count_with_max for A in [ [0,0,0,1],[0,0,0],[2,0,-2,2] ]: print kadane(A),kadane_count(A) </code></pre>
    singulars
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. VO
      singulars
      1. This table or related slice is empty.
    2. VO
      singulars
      1. This table or related slice is empty.
    3. VO
      singulars
      1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload