求数组最大的连续和
如果求连续的乘积和就要考虑负数相乘和0的情况……!
mi[1] = mx[1] = a[1]; for(int i = 2;i <= n;i++){ mi[i] = min(min(a[i],a[i]*mi[i-1]),a[i]*mx[i-1]); mx[i] = max(max(a[i],a[i] * mi[i-1]),a[i] * mx[i-1]); }
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
#include <iostream> #include <cstdio> #include <cmath> #include <cstring> #include <algorithm> #include <cstdlib> #include <stack> #include <cctype> #include <string> #include <malloc.h> #include <queue> #include <map> using namespace std; const int INF = 0xffffff; const double esp = 10e-8; const double Pi = 4 * atan(1.0); const int Maxn = 2000+10; const long long mod = 2147483647; const int dr[] = {1,0,-1,0,-1,1,-1,1}; const int dc[] = {0,1,0,-1,1,-1,-1,1}; typedef long long LL; LL gac(LL a,LL b){ return b?gac(b,a%b):a; } int a[10000]; int maxsum(int x,int y){ ///算法复杂nln(n),f(n) = 2 * f(n/2)+n,f(1) = 1; if(y-x == 1) return a[x]; int m = x + (y-x)/2; int mm = max(maxsum(x,m),maxsum(m,y)); int L = a[m-1]; int R = a[y-1]; int v = 0; for(int i = m-1;i > -1;i--){ v += a[i]; L = max(v,L); } v = 0; for(int i = m;i < y;i++){ v += a[i]; R = max(R,v); } return max(mm,L+R); } int main() { #ifndef ONLINE_JUDGE freopen("inpt.txt","r",stdin); #endif int n; while(~scanf("%d",&n)){ int s[10000]; memset(s,0,sizeof(s)); int mx = -0xfffff; int tt = -1; for(int i = 1;i <= n;i++){ scanf("%d",&a[i]); s[i] += (s[i-1] + a[i]); if(s[i] >= mx){ mx = s[i]; tt = i; } } int mi = a[1]; if(tt != -1){ for(int i = 2;i < tt;i++){ ///在已经找到的最大和的前面寻找最小值 mi = min(mi,[i]); } } cout << "D1:" << mx - mi << endl; int xx = maxsum(1,n+1); cout << "D2:"<< xx << endl; } return 0; }