[LeetCode] 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).

 1 class Solution {
 2 public:
 3     int maxProfit(vector<int> &prices) {
 4         // Start typing your C/C++ solution below
 5         // DO NOT write int main() function
 6         if (prices.size() == 0)
 7             return 0;
 8             
 9         vector<int> f1(prices.size());
10         vector<int> f2(prices.size());
11         
12         int minV = prices[0];
13         f1[0] = 0;
14         for(int i = 1; i < prices.size(); i++)
15         {
16             minV = min(minV, prices[i]);
17             f1[i] = max(f1[i-1], prices[i] - minV);
18         }
19         
20         int maxV = prices[prices.size()-1];
21         f2[f2.size()-1] = 0;
22         for(int i = prices.size() - 2; i >= 0; i--)
23         {
24             maxV = max(prices[i], maxV);
25             f2[i] = max(f2[i+1], maxV - prices[i]);
26         }
27         
28         int sum = 0;
29         for(int i = 0; i < prices.size(); i++)
30             sum = max(sum, f1[i] + f2[i]);
31             
32         return sum;
33     }
34 };
原文地址:https://www.cnblogs.com/chkkch/p/2795178.html