Best Time to Buy and Sell Stock III
2013-10-31 03:49
260 查看
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).
Code:
Method1:
Method2:
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).
Code:
Method1:
class Solution { public: int maxProfit(vector<int> &prices) { int oneTry=0,oneHis=0,twoTry=0,twoHis=0; //Try: attempt to buy; His: the max-profit record; One/Two: one/two transaction(s) int n = prices.size() - 1; for (int i=0;i<n;i++){ int diff = prices[i+1] - prices[i]; if(i>0){ twoTry = max(twoTry, oneHis) + diff; twoHis = max(twoTry,twoHis); // the max-profit by totally two transactions } oneTry = max(oneTry, 0) + diff; oneHis = max(oneTry,oneHis); // the max-profit by totally one transaction } return max(oneHis,twoHis); } };
Method2:
class Solution { public: int maxProfit(vector<int> &prices) { // null check int len = prices.size(); if (len==0) return 0; vector<int> historyProfit; vector<int> futureProfit; historyProfit.assign(len,0); futureProfit.assign(len,0); int valley = prices[0]; int peak = prices[len-1]; int maxProfit = 0; // forward, calculate max profit until this time for (int i = 0; i<len; ++i) { valley = min(valley,prices[i]); if(i>0) { historyProfit[i]=max(historyProfit[i-1],prices[i]-valley); } } // backward, calculate max profit from now, and the sum with history for (int i = len-1; i>=0; --i) { peak = max(peak, prices[i]); if (i<len-1) { futureProfit[i]=max(futureProfit[i+1],peak-prices[i]); } maxProfit = max(maxProfit,historyProfit[i]+futureProfit[i]); } return maxProfit; } };
相关文章推荐
- lintcode-medium-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
- LeetCode Best Time to Buy and Sell Stock I,II,III
- LeetCode Best Time to Buy and Sell Stock III(dp)
- [leetcode]Best Time to Buy and Sell Stock III
- 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
- LeetCode Best Time to Buy and Sell Stock III
- 【leetcode】123. Best Time to Buy and Sell Stock III【java】
- 123. Best Time to Buy and Sell Stock III
- Best Time to Buy and Sell Stock III
- Best Time to Buy and Sell Stock I && II && III
- [LeetCode] 123. Best Time to Buy and Sell Stock III 买卖股票的最佳时间 III
- LeetCode123 Best Time to Buy and Sell Stock III
- 【LeetCode】Best Time to Buy and Sell Stock III
- LeetCode OJ Best Time to Buy and Sell Stock I II III IV
- LeetCode题解系列--123. Best Time to Buy and Sell Stock III
- LeetCode之Best Time to Buy and Sell Stock III