题目:输入一个整形数组,数组里有正数也有负数。求所有子数组的和的最大值,并且时间复杂度为O(n)
个人代码:
#include<iostream>
using namespace std;
int main()
{
int length,sum=0,max=0;
cout<<"input the length of the array:"<<endl;
cin>>length;
int *a=new int[100];
for(int i=0;i!=length;++i)
{
cout<<"输入数字:"<<endl;
cin>>a[i];
}
for(int i=0;i!=length;++i)
{
sum+=a[i];
if(sum<0)
sum=0;
if(sum>max)
max=sum;//如果加上一个负数,则保留原来的最大值;如果加上一个正数,并且新的和值大于原来的最大值,则更换
}
cout<<"the max number of the children array:"<<max<<endl;
return 0;
}
for语句里的第一个if语句是判断前面的数字和是不是负数,如果是则前面的数字舍弃,从后面的数字开始算起,可以这样理解
把前面的数字看成一个整体,任何数加上一个负数都不可能比原先的数字要大,所以要求最大值,就不应该包含前面的和为负的那些数字。