返回一个二维整数数组中的最大子数组的和

#include<iostream>
using namespace std;
int max(int a,int b)
{
    if(a>b)
    {return a;
    }
    else 
    {return b;
    }
}
int maxsum(int a,int n)
{
    int i;
    int maxsofar=0;//maxsofar记录到目前为止的最大值
    int maxendinghere=0;//maxendinghere记录从当前位置开始网前几个连续的数的和的最大值
    for(i=0;i<n;i++)
    {
        maxendinghere=max(maxendinghere+a[i],0);
        maxsofar=max(maxsofar,maxendinghere);
    }
    return maxsofar;
}
int main()
{
    int n,a i=0;
    cout<<"请输入数组:";
        cin>>a[i];
    int max=maxsum(a,n);
    cout<<最大子数组的和为:"<<max<<endl;
        return 0;
}

猜你喜欢

转载自www.cnblogs.com/tengda123/p/9904922.html
今日推荐