###### tags: `Leetcode` `hard` `dynamic programming` `python`
# 123. Best Time to Buy and Sell Stock III
## [題目連結:] https://leetcode.com/problems/best-time-to-buy-and-sell-stock-iii/description/
## 題目:
You are given an array ```prices``` where ```prices[i]``` is the price of a given stock on the ```ith``` day.
Find the maximum profit you can achieve. You may complete **at most two transactions**.
**Note**: You may not engage in multiple transactions simultaneously (i.e., you must sell the stock before you buy again).
**Example 1:**
```
Input: prices = [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: prices = [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: prices = [7,6,4,3,1]
Output: 0
Explanation: In this case, no transaction is done, i.e. max profit = 0.
```
## 解題想法:
* 題目為要求,最多進行兩次買賣,求最大獲利:
* 一定要先買,才能賣
* 狀態為順序制度:
* 一定要先買第一次,才能賣第一次
* 賣完第一次,才能買第二次.....
* 不能連續買,一定要進行完一組交易後,才能再進行下一組
* 使用DP:
* 因為可以有兩次交易:
* 每天可能會有四種狀態,且皆只與前一天狀態有關
* 皆用max:表示最大獲利
* case1:
* 第一次買:
* firstB[i]=max(firstB[i-1], -prices[i-1])
* case2:
* 第一次賣:
* firstS[i]=max(firstS[i-1], firstB[i]+prices[i-1])
* case3:
* 第二次買:
* secondB[i]=max(secondB[i-1], firstS[i]-prices[i-1])
* case4:
* 第二次賣:
* secondS[i]=max(secondS[i-1], secondB[i]+prices[i-1])
## Python:
``` python=
class Solution(object):
def maxProfit(self, prices):
"""
:type prices: List[int]
:rtype: int
"""
n=len(prices)
firstB=[0 for _ in range(n+1)]
firstS=[0 for _ in range(n+1)]
secondB=[0 for _ in range(n+1)]
secondS=[0 for _ in range(n+1)]
firstB[0]=float('-inf')
secondB[0]=float('-inf')
for i in range(1,n+1):
firstB[i]=max(firstB[i-1], -prices[i-1])
firstS[i]=max(firstS[i-1], firstB[i]+prices[i-1])
secondB[i]=max(secondB[i-1], firstS[i]-prices[i-1])
secondS[i]=max(secondS[i-1], secondB[i]+prices[i-1])
return secondS[-1]
if __name__=='__main__':
result=Solution()
ans=result.maxProfit(prices = [3,3,5,0,0,3,1,4])
print(ans) #6
```