/*
*author: Jack.xu/nanac.xu
*date: 08/26/2009
*function: max subsequence sum
*/
#include
#include
namespace dskit{
-
/*with O(N) time complexity*/
int MSS(const ELEMENTSTYPE* elements, size_t size)
{
assert(NULL != elements);
int the_sum = 0;
int max_sum = 0;
for(int i = 0; i != size; ++i)
{
the_sum += elements[i];
if(the_sum > max_sum)
max_sum = the_sum;
else if(the_sum < 0)
the_sum = 0;
}
return max_sum;
}
-
/*divided algorithm with O(NlogN) time complexity*/
int MSS_divide(const ELEMENTSTYPE* elements, size_t begin, size_t end)
{
assert(NULL != elements && begin >= 0 && end >= 0);
if(begin == end)
{
if(elements[begin] < 0)
return 0;
else
return elements[begin];
}
-
-
size_t center = ((begin + end) >> 1);
-
int left_max = MSS_divide(elements, begin, center);
int right_max = MSS_divide(elements, center + 1, end);
-
int temp_sum = 0;
int center_left_max = 0;
for(int i = center; i >= begin; i--)
{
if(i < 0)
break;
temp_sum += elements[i];
if(temp_sum > center_left_max)
center_left_max = temp_sum;
}
-
temp_sum = 0;
int center_right_max = 0;
for(int i = center + 1; i <= end; i++)
{
temp_sum += elements[i];
if(temp_sum > center_right_max)
center_right_max = temp_sum;
}
-
temp_sum = (left_max > right_max) ? left_max : right_max;
-
return (temp_sum > (center_right_max + center_left_max)) ? temp_sum : (center_right_max + center_left_max);
}
-
}
-
-
#ifndef NDEBUG
int main(int argc, char* argv[])
{
ELEMENTSTYPE array[] = {-1, 1, 32, 3, 4, -23, 24};
-
std::cout << dskit::MSS(array, sizeof(array) / sizeof(ELEMENTSTYPE)) << std::endl;
std::cout << dskit::MSS_divide(array, 0, sizeof(array) / sizeof(ELEMENTSTYPE) - 1) << std::endl;
return 0;
}
-
#endif