题目:给定一个数字序列 A1,A2…An,求 i,j(1<=i<=j<=n),使得 Ai+…+Aj 最大,
输出这个最大和。
例:
输入:
6
-2 11 -4 13 -5 -2
输出:
20
- 思路分析
求某几个连续数字的和,并输出这个最大值
想到利用双循环,依次求出每一个组合的和,并存储到一个数组中,最后输出数组中的最大值 - 代码
#include<iostream>
#include<algorithm>
using namespace std;
int cmp(int a,int b){
return a>b;
}
int main(){
int n,i,j;
cin>>n;
int a[n];
for(i=0;i<n;i++)
cin>>a[i];
int b[n];
for(i=0;i<n;i++){
int max=a[0];
int tmp=0;
for(j=i;j<n;j++){
tmp+=a[j];
if(tmp>max){
max=tmp;
}
}
b[i]=max;
}
sort(b,b+n,cmp);
cout<<b[0];
return 0;
}