https://oj.leetcode.com/problems/best-time-to-buy-and-sell-stock-iii/
这题没做出来,看了网上的分析才做出来的。。。关键点就是要利用on-line算法的性质,避免重复计算。
class Solution {
public:
int maxProfit(vector<int> &prices) {
if (prices.size() < 2) {
return 0;
}
vector<int> max_profile1; max_profile1.reserve(prices.size() + 1); // max_profile1[i] : max profit of [0, i]
vector<int> max_profile2; max_profile2.reserve(prices.size() + 1); // max_profile2[i] : max profit of [i, end];
max_profile1[0] = 0;
int low = prices[0], temp = 0;
for (int i = 1, end = prices.size(); i < end; ++i) {
if (prices[i] < low ) { low = prices[i]; }
if (prices[i] - low > temp) { temp = prices[i] - low; }
max_profile1[i] = temp;
}
max_profile2[prices.size()] = 0;
int hi = prices[prices.size()-1]; temp = 0;
for (int i = prices.size() - 1; i >= 0; --i) {
if (hi < prices[i]) { hi = prices[i]; }
if (temp < hi - prices[i]) { temp = hi - prices[i]; }
max_profile2[i] = temp;
}
int max_profile = 0;
for (vector<int>::size_type i = 0, end = prices.size(); i < end; ++i) {
if (max_profile < max_profile1[i] + max_profile2[i+1]) {
max_profile = max_profile1[i] + max_profile2[i+1];
}
}
return max_profile;
}
};