计算一个整形数组里的连续元素和的最大值

来源:互联网 发布:在线考试系统java案例 编辑:程序博客网 时间:2024/06/06 11:12

void max_sum(int *a, int len, int &low, int &high, int &max)
{
  int temp_max = 0;
  int temp_sum = 0;
  int i = 0;
  int temp_l =0, temp_h = 0;
  for (; i < len; i++)
  {
    if (a[i] < 0)
    {
      if (temp_max > max)
      {
        low = temp_l;
        high = i - 1;
        max = temp_max;
      }
      if (temp_max + a[i] > 0)
      {
        temp_max += a[i];
      }
      else
      {
        temp_max = 0;
        temp_l = i + 1;
      }
    }
    else
    {
      temp_max += a[i];
    }
  }
  temp_max = 0;
  for (int i = temp_l; i < len; i++)
  {
    temp_max += a[i];
  }
  if(temp_max > max)
  {
    low = temp_l;
    high = len - 1;
    max = temp_max;
  }
}