您的位置:首页 > 其它

LeetCode OJ:Best Time to Buy and Sell Stock III

2014-01-20 23:13 399 查看


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).

算法思想:

dp1[i]存储前i个元素的最长连续子序列和;

dp2[i]存储i至n-1元素的最长连续子序列和

那么最后答案为max{dp1[i]+dp2[i]},0<=i<n

class Solution{
public:
int maxProfit(vector<int> &prices){
if(!prices.size())return 0;
vector<int> dp1(prices.size());
vector<int> dp2(prices.size());
dp1[0]=0;
int minP=prices[0];
for(int i=1;i<prices.size();i++){
minP=min(minP,prices[i]);
dp1[i]=max(dp1[i-1],prices[i]-minP);
}
int maxP=prices[prices.size()-1];
dp2[prices.size()-1]=0;
for(int i=prices.size()-2;i>=0;i--){
maxP=max(maxP,prices[i]);
dp2[i]=max(dp2[i+1],maxP-prices[i]);
}
maxP=0;
for(int i=0;i<prices.size();i++)maxP=max(maxP,dp1[i]+dp2[i]);
return maxP;
}
};
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: