1

The problem found in programming pearls column 8 is as follows:

Given the real vector x[n], compute the maximum sum found in any contiguous subvector.

The final solution provided is of O(n) complexity which is as follows:

std::vector<int> x;
int max_so_far = 0;
int max_here = 0;
for (std::size_t i = 0; i < x.size(); ++i)
{
   max_here = std::max(max_here + x[i], 0);
   max_so_far = std::max(max_so_far, max_here);
}

I would like to know how does one go about modifing the above algorithm to provide the minimum sum.

  • 4
    Set x[n] = -x[n] and run the max sum... –  Feb 07 '11 at 23:28
  • You could multiply all vector elements by -1, run the vector through the code above, and again multiply the sum found by -1. – toochin Feb 07 '11 at 23:29
  • @Reyzooti - I have a doubt. Does the term "subvector" include only the vectors starting from position 0? – Neo Feb 07 '11 at 23:41
  • If your vector contains all negative numbers, your code will fail. It will report that the maximum value is 0. Correct that by making the initial value of `max_so_far` equal to the lowest integer. – Jim Mischel Feb 08 '11 at 00:01
  • @Jim: I got the algorithm from here: http://netlib.bell-labs.com/cm/cs/pearls/s08.pdf So there must be an error in the hard copy too perhaps? –  Feb 08 '11 at 00:16
  • 2
    @Jim: if subvector may include a subvector of length zero, then 0 is indeed the maximum sum when all numbers are negative. So it's correct. – DS. Feb 08 '11 at 01:47

1 Answers1

2

You only need to invert the sign of each element in x and then run the algorithm:

std::vector<int> x;
int max_so_far = 0;
int max_here = 0;

for (std::size_t i = 0; i < x.size(); ++i) x[i] = -x[i];

for (std::size_t i = 0; i < x.size(); ++i)
{
   max_here = std::max(max_here + x[i], 0);
   max_so_far = std::max(max_so_far, max_here);
}

int min_so_far = -max_so_far;
Murilo Vasconcelos
  • 4,677
  • 24
  • 27
  • This will not work. max of negative and zero will always be zero. – Neo Feb 07 '11 at 23:34
  • @Neo: yes, because of that I inverted the sign of `x`'s elements. – Murilo Vasconcelos Feb 07 '11 at 23:36
  • @Moron - Exactly. Thats what confused me. – Neo Feb 07 '11 at 23:42
  • If all elements are negative, it will return 0. We should start with max_so_far = max_here = -infinity... Of couse, you _could_ consider a subvector of _no_ elements as having sum zero and consider that valid output. –  Feb 07 '11 at 23:50
  • The maximum sum of a subarray of 0 elements is 0, since you'd sum nothing. – Murilo Vasconcelos Feb 08 '11 at 00:00
  • @MUrilo: If you have an array of 10 elements, and you considered subarrays of _zero_ elements, then the algorithm is valid. Perhaps we are saying the same thing. Anyway... –  Feb 08 '11 at 00:26