0

Let's say we have an array of n real numbers. We want to find the longest contiguous subsequence in the array that it's sum is greater or equal zero.

It has to be done in linear time.

We actually have no idea how to start answering this.

Thanks in advance.

user76508
  • 267
  • 2
  • 8

1 Answers1

1

For this, create a subsequence (here designated with ibeg, iend, and length len) and basically march along the sequence, extending the subsequence at the end or shrinking it at the beginning to maintain >0. Since the inner loop is constrained by the length of the current sequence it is still O(N).

var ibeg = 0;
var iend = 0;
var len = 0;
var best_len = -1, best_ibeg = 0, best_iend = 0;

var acc = 0;
var i = 0;
var N = length(sequence);
while i<N
   acc += sequence(i);
   len++;
   iend++;
   if acc>0
      if len>best_len
          best_len = len;
          best_ibeg = ibeg;
          best_iend = iend;
      end
   else
      while ibeg<=iend
          acc -= sequence(ibeg);
          ibeg++;
          if acc>0, break; end
      end
   end
end

Then best_len will be the length of the longest sequence, and best_ibeg and best_iend will be where it starts and ends, respectively.

Matt Phillips
  • 9,465
  • 8
  • 44
  • 75
  • what if i found a good contiguous subsequence and then i find another one. maybe adding them together is better – user76508 Jun 27 '14 at 12:47
  • If you add two contiguous but separate subsequences together, the result won't be contiguous, and so won't be an acceptable answer for you as I understand your problem. – Matt Phillips Jun 27 '14 at 12:49
  • it will be because maybe id rather add them both and the bad part between them... – user76508 Jun 27 '14 at 12:54
  • 1
    @user76508 Right, I think basically what you're saying is that the above algorithm will only find 'local maxima' and may miss a global maximum. I think you are right. But perhaps there is a way to modify it to accommodate this situation, I will post it if I think of one, for now, the above is at least a start. – Matt Phillips Jun 27 '14 at 13:02