1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
// @Title: 买卖股票的最佳时机 III (Best Time to Buy and Sell Stock III)
// @Author: 15816537946@163.com
// @Date: 2021-01-09 17:49:46
// @Runtime: 188 ms
// @Memory: 8.7 MB
func maxProfit(prices []int) int {
	buy1, sell1 := -prices[0], 0
	buy2, sell2 := -prices[0], 0

	for i := 1; i < len(prices); i++ {
		buy1 = max(buy1, -prices[i])
		sell1 = max(sell1, buy1+prices[i])
		buy2 = max(buy2, sell1-prices[i])
		sell2 = max(sell2, buy2+prices[i])
	}

	return sell2

}

func max(a, b int) int {
	if a > b {
		return a
	}
	return b
}