代码:
#include <iostream> #include <cmath> #include <vector> using namespace std; vector<int> prices; int calculateMax(vector<int> prices) { int i,nmin,nmax,len,ans; len=prices.size(); int *lhs=new int[len]; int *rhs=new int[len]; lhs[0]=0; nmin=prices[0]; for(i=1;i<len;i++) { lhs[i]=max(lhs[i-1],prices[i]-nmin); if(prices[i]<nmin) nmin=prices[i]; // cout<<"lhs "<<i<<" "<<lhs[i]<<endl; } rhs[len-1]=0; nmax=prices[len-1]; for(i=len-2;i>=0;i--) { rhs[i]=max(rhs[i+1],nmax-prices[i]); if(prices[i]>nmax) nmax=prices[i]; // cout<<"rhs "<<i<<" "<<rhs[i]<<endl; } ans=0; for(i=0;i<len;i++) if((lhs[i]+rhs[i])>ans) ans=lhs[i]+rhs[i]; return ans; } int main() { int m,len; while(cin>>m) prices.push_back(m); cout<<calculateMax(prices)<<endl; return 0; }
下面是去掉注释的测试截图,可以直观一点
原文地址:http://blog.csdn.net/u011694809/article/details/46397941