思路:III限制了只能进行两次交易,问题可以转化成在两个不重叠区间找到i和j(i<j)可以使Aj - Ai,即在区间[0..i]和[i..n-1]两个区间寻找最优的一次交易。时间复杂度是O(N^2),可以优化分别用O(N)的时间计算[0..i]和[i..n-1]。
class Solution {
public:
int maxProfit(vector<int> &prices) {
// Start typing your C/C++ solution below
// DO NOT write int main() function
if(prices.size() < 2) return 0;
vector<int> f(prices.size());
vector<int> g(prices.size());
int ans = 0;
{
int minVal = prices.front();
int ans = 0;
for(vector<int>::size_type i = 0; i < prices.size(); ++i)
{
minVal = min(minVal, prices[i]);
ans = max(ans, prices[i] - minVal);
f[i] = ans;
}
}
{
int maxVal = prices.back();
int ans = 0;
for(int i = prices.size() - 1; i >= 0; --i)
{
maxVal = max(maxVal, prices[i]);
ans = max(ans, maxVal - prices[i]);
g[i] = ans;
}
}
ans = 0;
for(int i = 0; i < prices.size(); ++i)
ans = max(ans, f[i] + g[i]);
return ans;
}
};