本文为senlie原创,转载请保留此地址:http://blog.csdn.net/zhengsenlie
Best Time to Buy and Sell Stock III
Total Accepted: 8447 Total Submissions: 38417Say 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).
题意:给定一组数,表示某个股票每天的价格,问怎么买卖可获得最大利益。最多可以买卖再次
思路:分段动规
因为最多可买卖两次,所以可分将数组两段,每段取最大利益
设i将[1,n]分为[1,i]和[i,n](如果第一段在i卖,第二段在i买,则两段合为一段)
f[i]表示以i为结尾的最大利益
f[i] = max(f[i - 1], prices[i] - cur_min_price), cur_min_price表示当前最小价格
从0到n,求f[i]
g[i]表示以i为开头的最大利益
g[i] = max(g[i + 1], cur_max_price - prices[i]), cur_max_price表示当前最大价格
从n到n,求g[i]
因为最多可以买卖两次,即可以少于两次,所以允许在一天内既买又卖,即不交易。
这点体现在在求f[i],g[i]的时候,先求cur_min_price,cur_max_price,再求f[i],g[i],
最后的结果为
max{f(i) + g(i)}
复杂度:O(n)
class Solution {
public:
int maxProfit(vector<int> &prices){
int n = prices.size();
if(n < 2) return 0;
vector<int> f(n, 0);
vector<int> g(n, 0);
for(int i = 1, cur_min_price = prices[0]; i < n; i++){
cur_min_price = min(cur_min_price, prices[i]);
f[i] = max(f[i - 1], prices[i] - cur_min_price);
}
for(int j = n - 2, cur_max_price = prices[n - 1]; j > -1; j--){
cur_max_price = max(cur_max_price, prices[j]);
g[j] = max(g[j + 1], cur_max_price - prices[j]);
}
int max_profit = 0;
for(int i = 0; i < n; i++){
max_profit = max(max_profit, f[i] + g[i]);
}
return max_profit;
}
};