纯转载……
和前两道题比起来的话,这道题最难了,因为限制了交易次数。
解决问题的途径我想出来的是:既然最多只能完成两笔交易,而且交易之间没有重叠,那么就divide and conquer。
设i从0到n-1,那么针对每一个i,看看在prices的子序列[0,...,i][i,...,n-1]上分别取得的最大利润(第一题)即可。
这样初步一算,时间复杂度是O(n2)。
改进:
改进的方法就是动态规划了,那就是第一步扫描,先计算出子序列[0,...,i]中的最大利润,用一个数组保存下来,那么时间是O(n)。
第二步是逆向扫描,计算子序列[i,...,n-1]上的最大利润,这一步同时就能结合上一步的结果计算最终的最大利润了,这一步也是O(n)。
所以最后算法的复杂度就是O(n)的。
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).
代码:12ms过大集合,一次性bug free,很happy
class Solution { public: int maxProfit(vector<int> &prices) { // Start typing your C/C++ solution below // DO NOT write int main() function if(prices.size() <= 1) return 0; //stores the max profit in [0, ... , i] subarray in prices vector<int> maxEndWith; {//build the maxEndWith. int lowest = prices[0]; int maxprofit = 0; maxEndWith.push_back(0); for(int i = 1; i < prices.size(); ++i) { int profit = prices[i] - lowest; if(profit > maxprofit) { maxprofit = profit; } maxEndWith.push_back(maxprofit); if(prices[i] < lowest) lowest = prices[i]; } } int ret = maxEndWith[prices.size() - 1]; {//reverse to see what is the maxprofit of [i, ... , n-1] subarray in prices //and meanwhile calculate the final result int highest = prices[prices.size() - 1]; int maxprofit = 0; for(int i = prices.size() - 2; i >= 0; --i) { int profit = highest - prices[i]; if(profit > maxprofit) maxprofit = profit; int finalprofit = maxprofit + maxEndWith[i]; if(finalprofit > ret) ret = finalprofit; if(prices[i] > highest) highest = prices[i]; } } return ret; } };
下面是自己的代码:
class Solution {
public:
int maxProfit(vector<int> &prices)
{
if (prices.size() < 2)
return 0;
vector<int> prof;
int maxProf(0);
int tm(prices[0]);
int revprof(0);
prof.push_back(0);
for (int i = 1; i < prices.size(); i++)
{
tm = std::min(tm, prices[i]);
prof.push_back(std::max(prof[i - 1], prices[i] - tm));
}
tm = prices[prices.size() - 1];
for (int i = prices.size() - 2; i >= 0; i--)
{
tm = std::max(prices[i], tm);
revprof = std::max(revprof, tm - prices[i]);
maxProf = std::max(maxProf, revprof + prof[i]);
}
return maxProf;
}
};