2015 Xiaomi summer internship exam _ tuyere pig-China bull market (dp), 2015dp
In the air, pigs can fly. Today's China stock market bull market is really a "missed seven years ". This gives you a chance to review history. We know the price trend of a stock for n consecutive days, represented by an integer array of n in length. The I element in the array (prices [I]) represents the stock price on the day I. Assume that you have no stock at first, but you have the chance to buy one stock at most twice and then sell one stock at most, and you must ensure that you have no stock before buying. If both trading opportunities are abandoned, the return is 0. Design algorithms to calculate the maximum benefits you can get.
Input value range: 2 <= n <= 100, 0 <= prices [I] <=
Input example:
3, 8, 5, 1, 7, 8
Output example:
12
Code:
#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;}
The following is a test to remove comments, which is more intuitive.