# 123. Best Time to Buy and Sell Stock III

**<font color=red>难度:Hard<font>**

## 刷题内容
> 原题连接

* https://leetcode.com/problems/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 (i.e., you must sell the stock before you buy again).

Example 1:

Input: [3,3,5,0,0,3,1,4]
Output: 6
Explanation: Buy on day 4 (price = 0) and sell on day 6 (price = 3), profit = 3-0 = 3.
             Then buy on day 7 (price = 1) and sell on day 8 (price = 4), profit = 4-1 = 3.
Example 2:

Input: [1,2,3,4,5]
Output: 4
Explanation: Buy on day 1 (price = 1) and sell on day 5 (price = 5), profit = 5-1 = 4.
             Note that you cannot buy on day 1, buy on day 2 and sell them later, as you are
             engaging multiple transactions at the same time. You must sell before buying again.
Example 3:

Input: [7,6,4,3,1]
Output: 0
Explanation: In this case, no transaction is done, i.e. max profit = 0.
```

> 思路1
******- 时间复杂度: O(n^2)******- 空间复杂度: O(n)******

与之前的不同，这次需要交易两次，因此我们用记忆化的方法记录下第i天的之后交易的最大值，这就是第二次每天交易之后的最大值，接着只要遍历数组，求出第一天交易最大值，第一个方法我枚举了每次交易，求出了最大值。

```cpp
class Solution {
public:
    int maxProfit(vector<int>& prices) {
        int len = prices.size();
        if(!len)
            return 0;
        int arr[len + 1];
        memset(arr,0,sizeof(arr));
        int max1 = prices[len - 1],price = 0;
        for(int j = len - 2;j >= 0;--j)
        {
            if(prices[j] > max1)
                max1 = prices[j];
            arr[j] = max(arr[j + 1],max1 - prices[j]);
        }
        int ret = 0;
        for(int i = 0;i < len;++i)
            for(int j = i + 1;j < len;++j)
                if(prices[j] > prices[i])
                    ret = max(ret,prices[j] - prices[i] + arr[j + 1]);
        return ret;
    }
};
```
> 思路2
******- 时间复杂度: O(n)******- 空间复杂度: O(n)******

第二种方法就是对思路1进行了优化，再求第一次交易时定义一个最小值min1，代表了第i天之前的最小值，之后遍历数组，每次更新min1，求得prices[i] - min1的最大值即可

```cpp
class Solution {
public:
    int maxProfit(vector<int>& prices) {
        int len = prices.size();
        if(!len)
            return 0;
        int arr[len + 1];
        memset(arr,0,sizeof(arr));
        int max1 = prices[len - 1],price = 0;
        for(int j = len - 2;j >= 0;--j)
        {
            if(prices[j] > max1)
                max1 = prices[j];
            arr[j] = max(arr[j + 1],max1 - prices[j]);
        }
        int ret = 0;
        int min1 = prices[0];
        for(int i = 0;i < len;++i)
        {
            if(prices[i] < min1)
                min1 = prices[i];
            ret = max(ret,prices[i] - min1 + arr[i + 1]);
        }
        return ret;
    }
};