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; } };
相关文章推荐
- 【LeetCode OJ】Best Time to Buy and Sell Stock III
- LeetCode OJ - Best Time to Buy and Sell Stock III
- LeetCode OJ 123 Best Time to Buy and Sell Stock III
- LeetCode OJ - Best Time to Buy and Sell Stock III
- LeetCode OJ--Best Time to Buy and Sell Stock III
- LeetCode OJ 123 Best Time to Buy and Sell Stock III
- [LeetCode] Best Time to Buy and Sell Stock III
- 【leetcode】123. Best Time to Buy and Sell Stock III【java】
- 【leetcode】123. Best Time to Buy and Sell Stock III
- Best Time to Buy and Sell Stock | & || & III
- 123. Best Time to Buy and Sell Stock III(贪心,hard)
- Best Time to Buy and Sell Stock III -- LeetCode
- Best Time to Buy and Sell Stock III 解题思路
- [leetcode 123] Best Time to Buy and Sell Stock III
- 【Leetcode】Best Time to Buy and Sell Stock III (DP)
- [LeetCode] 123. Best Time to Buy and Sell Stock III 买卖股票的最佳时间 III
- Best Time to Buy and Sell Stock III
- [LeetCode]Best Time to Buy and Sell Stock III
- leetcode - Best Time to Buy and Sell Stock III
- 123. Best Time to Buy and Sell Stock III