Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    primarykey
    data
    text
    <p>This problem is the topic of column 7 in Jon Bentleys celebrated "Programming Pearls". The solution is an algorithm with a run time of O(n), where n is the length of the vector x.</p> <p>An R implementation can solve a vector of millions of elements in less than 3 seconds:</p> <pre><code>x &lt;- rnorm(1e6) system.time(m &lt;- maxsub(x)) </code></pre> <p>If you want the negative sums, too, call maxsub(-x). It's easy to change the code such that the function will return the indices. The two ranges cannot overlap, but one can be a part of the other.</p> <pre><code>maxsub &lt;- function(x) { if (!is.numeric(x)) stop("Argument 'x' must be a numeric vector.") m1 &lt;- m2 &lt;- 0.0 for (i in 1:length(x)) { m2 &lt;- max(m2 + x[i], 0.0) m1 &lt;- max(m1, m2) } return(m1) } </code></pre> <p>Though the code looks so simple, it took quite a long time until someone came up with this solution, as Bentley reports. A corresponding algorithm for the two-(or higher)dimensional case has not yet been found.</p> <p>Update: Here is a version that also returns the indices. It looks complicated, but is not. It simply keeps track of the indices in each of the two steps above.</p> <pre><code>maxsub &lt;- function(x, inds = FALSE) { if (!is.numeric(x)) stop("Argument 'x' must be a numeric vector.") n &lt;- length(x) if (!inds) { m1 &lt;- m2 &lt;- 0.0 for (i in 1:n) { m2 &lt;- max(m2 + x[i], 0.0) m1 &lt;- max(m1, m2) } return(m1) } else { m1 &lt;- m2 &lt;- 0 p1 &lt;- p2 &lt;- 0 q1 &lt;- q2 &lt;- 1 for (i in 1:n) { if (m2 &gt; -x[i]) { m2 &lt;- m2 + x[i] q2 &lt;- i if (m2 &gt; m1) { m1 &lt;- m2 p1 &lt;- q1; p2 &lt;- q2 } } else { m2 &lt;- 0 q1 &lt;- q2 &lt;- i+1 } } return(list(sum = m1, inds = c(p1, p2))) } } </code></pre> <p>A Fortran version bounded to an R package does solve a million elements in 0.015 secs.</p>
    singulars
    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. 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.
 

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