代码改变世界

求有最大和的子数组

2009-10-17 09:29  Iron  阅读(188)  评论(0编辑  收藏  举报
#include <iostream>
using namespace std;
int x[5] = {-1,5,-3,2,8};
int main()
{
 int start,end;
 int tempstart,tempend;
 start = end = tempend = tempstart = 0;
 int sum;
 int tempsum;
 sum = tempsum =0;
 for (int i = 0; i<_countof(x); ++i)
 {
  if (x[i]>0)
  {
   if (sum==0)
   {
    start = end = i;
    tempstart = tempend = i;
    sum += x[i];
    tempsum += x[i];
   }
   else
   {
    tempsum += x[i];
    tempend = i;
    if (tempsum > sum)
    {
     start = tempstart;
     end = tempend;
     sum = tempsum;
    }
   }
  }
  else
  {
   tempsum += x[i];
   tempend = i;
   if (tempsum < 0)
   {
    tempstart = tempend = i+1;
    tempsum = 0;
   }
  }
 }

 cout << start << " " << end << endl;
}