---
# System prepended metadata

title: 0123. Best Time to Buy and Sell Stock III
tags: [Leetcode, Dynamic Programming, Hard]

---

# 0123. Best Time to Buy and Sell Stock III
###### tags: `Leetcode` `Hard` `Dynamic Programming`
Link: https://leetcode.com/problems/best-time-to-buy-and-sell-stock-iii/
## 思路
先忽略初始情况
可以发现每一天只有4种可能性 买了第一股 卖了第一股 买了第二股 卖了第二股
![](https://i.imgur.com/vhWTuPE.png)
由于如果手里还有股票没卖 一定比都卖了收益小 所以最后只要比较卖了第一股和卖了第二股的结果就可以

然后再用图里面最左边的箭头解决初始情况
## Code
```java=
class Solution {
    public int maxProfit(int[] prices) {
        int haveFirst = Integer.MIN_VALUE, haveSecond = Integer.MIN_VALUE;
        int soldFirst = 0, soldSecond = 0;
        int len = prices.length;
        for(int i=0; i<len; i++){
            haveFirst = Math.max(haveFirst, -prices[i]);
            soldFirst = Math.max(soldFirst, haveFirst+prices[i]);
            haveSecond = Math.max(haveSecond, soldFirst-prices[i]);
            soldSecond = Math.max(soldSecond, haveSecond+prices[i]);
        }
        return Math.max(soldFirst, soldSecond);
    }
}
```