最大子列和问题-4种解法
1.暴力求解
2.稍稍改进
#include <bits/stdc++.h> using namespace std; int main() { int n; int a[100001]; int maxsum=0,sum; int i,j,k; cin>>n; for(i=0;i<n;i++) cin>>a[i]; for(i=0;i<n;i++) for(j=i;j<n;j++) { sum=0; for(k=i;k<=j;k++) { sum+=a[k]; } if(sum>maxsum) maxsum=sum; } cout<<maxsum<<endl; return 0; }
2.稍稍改进
//稍稍改进 #include <bits/stdc++.h> using namespace std; int main() { int n; int a[100001]; int maxsum=0,sum; int i,j,k; cin>>n; for(i=0;i<n;i++) cin>>a[i]; for(i=0;i<n;i++) { sum=0; for(j=i;j<n;j++) { sum+=a[j]; //避免重复计算 if(sum>maxsum) maxsum=sum; } } cout<<maxsum<<endl; return 0; }
3.分治法
//分治法 #include <iostream> using namespace std; int maxcross(int a[],int left,int mid,int right) { int leftsum=0,rightsum=0,sum=0; int i; for(i=mid;i>=left;i--) { sum+=a[i]; if(sum>leftsum) leftsum=sum; } sum=0; for(i=mid+1;i<=right;i++) { sum+=a[i]; if(sum>rightsum) rightsum=sum; } return rightsum+leftsum; } int max(int x,int y,int z) { if(x>=y&&x>=z) return x; else if(y>=x&&y>=z) return y; else if(z>=y&&z>=x) return z; } int maxsubsequencesum(int a[],int left,int right) { if(left==right) { if(a[left]>0) return a[left]; else return 0; } int mid=(left+right)/2; int x,y,z; x=maxsubsequencesum(a,left,mid); y=maxsubsequencesum(a,mid+1,right); z=maxcross(a,left,mid,right); return max(x,y,z); } int main() { int n; int i; int a[100001]; cin>>n; for(i=0;i<n;i++) cin>>a[i]; cout<<maxsubsequencesum(a,0,n-1)<<endl; return 0; }
4.在线处理
#include <stdio.h> int main() { int n; int a[100001]; int sum=0; int max=0; int i; scanf("%d",&n); for(i=0;i<n;i++) { scanf("%d",&a[i]); } for(i=0;i<n;i++) { sum+=a[i]; if(sum<0) sum=0; if(sum>max) max=sum; } printf("%d",max); return 0; }