Re: Minimum sub-sequence sum



Michael Jarrod writes:
I have a sequence of integers (positive/negative values) and i would
like to find the sub sequence of consecutive values that yields the
smallest sum, I can think of a very simple O(n^3) complex solution,
however I was wondering are there any better solutions?

O(n): Walk through the sequence once, tracking whether the last negative
number should be included in the answer if the next negative number is.

def minsum_seq(seq):
total, found_total, found, seq = 0, 0, (0, -1), list(seq)
for index_of_val, val in enumerate(seq):
if total >= 0:
start_index, total = index_of_val, val
else:
total += val
if total < found_total:
found_total, found = total, (start_index, index_of_val)
return seq[found[0] : found[1] + 1]

--
Hallvard
.



Relevant Pages

  • Re: Minimum sub-sequence sum
    ... like to find the sub sequence of consecutive values that yields the ... smallest sum, I can think of a very simple Ocomplex solution, ...
    (sci.math)
  • Re: Minimum sub-sequence sum
    ... like to find the sub sequence of consecutive values that yields the ... smallest sum, I can think of a very simple Ocomplex solution, ... subquadratic algorithms as well as two quadratic algorithms he ...
    (comp.theory)
  • Minimum sub-sequence sum
    ... like to find the sub sequence of consecutive values that yields the ... smallest sum, I can think of a very simple Ocomplex solution, ...
    (sci.math)
  • Minimum sub-sequence sum
    ... like to find the sub sequence of consecutive values that yields the ... smallest sum, I can think of a very simple Ocomplex solution, ...
    (comp.programming)
  • Minimum sub-sequence sum
    ... like to find the sub sequence of consecutive values that yields the ... smallest sum, I can think of a very simple Ocomplex solution, ...
    (comp.theory)