123. Best Time to Buy and Sell Stock III
Say you have an array for which the ith element is the price of a given stock on day i.
Design an algorithm to find the maximum profit. You may complete at most two transactions.
Note:
You may not engage in multiple transactions at the same time (ie, you must sell the stock before you buy again).
Subscribe to see which companies asked this question
第一次用dp写n^2挂了。超时。后来 看的讨论里面的代码。太弱了
class Solution { public: int maxProfit(vector<int>& prices) { int n=prices.size(); if(n<=1)return 0; int dp1[n]={0}; int dp2[n]={0}; int Min=prices[0]; for(int i=1;i<n;i++){ dp1[i]=max(dp1[i-1],prices[i]-Min); Min=min(Min,prices[i]); } int Max=prices[n-1]; for(int i=n-2;i>=0;i--){ dp2[i]=max(dp2[i+1],Max-prices[i]); Max=max(Max,prices[i]); } int ans=0; for(int i=0;i<n;i++){ ans=max(ans,dp1[i]+dp2[i]); } return ans; } };
原文地址:http://www.cnblogs.com/pk28/
与有肝胆人共事,从无字句处读书。
欢迎关注公众号:
欢迎关注公众号: