编程之美2.14扩展问题2 求数组的子数组之和的最大值并给出子数组的起始终止位置

来源:互联网 发布:海信电视直播软件 编辑:程序博客网 时间:2024/05/21 12:48

#include <iostream>
#include <assert.h>
#include <fstream>
#include <stdio.h>
#include <string.h>
using namespace std;
int maxSum(int *a,int n,int &start,int &end)
{
 if(n<=0)
 {
  return 0;
 }
 int maxSum=a[n-1],sum=a[n-1];
 start=n-1; end=n-1;
 for(int i=n-2;i>=0;i--)
 {
  if(sum<=0)
  {
   end=i;
   sum=0;
  }
  sum+=a[i];
  if(sum>maxSum)
  {
   maxSum=sum;
       start=i;
  }
 }
 return maxSum;
}
int main()
{
 int a[]={1,-2,3,5,-3,2};
 int n=6;
 int start,end;
 int sum=maxSum(a,n,start,end);
 cout<<"最大值是 "<<sum<<"开始位置是 "<<start<<"结束位置是 "<<end<<endl;
 getchar();
 return 0;
}