2015 Xiaomi summer internship exam _ tuyere pig-China bull market (dp), 2015dp

Source: Internet
Author: User

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.





Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.