Loading... 这个题目总共能买卖两次,且必须要先卖掉第一次才能买第二次的,所以可以从左往右扫描获得 [0, i] 的最大盈利,从右往左扫描 [i, n-1] 的最大盈利,然后 left[i] + right[i] 的最大值就是两次购买的最大盈利了。 ```go func maxProfit(prices []int) int { n := len(prices) minLeft := prices[0] left := make([]int, n) for i := 1; i < n; i++ { if prices[i] < minLeft { minLeft = prices[i] } left[i] = max(left[i-1], prices[i]-minLeft) } maxRight := prices[len(prices)-1] right := make([]int, n) for i := n-2; i >= 0; i-- { if prices[i] > maxRight { maxRight = prices[i] } right[i] = max(right[i+1], maxRight-prices[i]) } res := 0 for i := 0; i < n; i++ { res = max(res, left[i]+right[i]) } return res } ``` Last modification:July 13, 2025 © Allow specification reprint Support Appreciate the author AliPayWeChat Like 如果觉得我的文章对你有用,请随意赞赏