309.best-time-to-buy-and-sell-stock-with-cooldown.go 447 B

123456789101112131415161718192021222324252627
  1. func maxProfit(prices []int) int {
  2. // v-.
  3. // >s0_|rest
  4. // / \
  5. // rest/ \ buy
  6. // / sell v
  7. // s2<-----s1<.
  8. // |_|rest
  9. //
  10. n := len(prices)
  11. if n <= 1 {
  12. return 0
  13. }
  14. s0, s1, s2 := 0, -prices[0], -1<<32
  15. for i := 1; i < n; i++ {
  16. s0, s1, s2 = maxInt(s0, s2), maxInt(s0-prices[i], s1), s1+prices[i]
  17. }
  18. return maxInt(s0, s2)
  19. }
  20. func maxInt(x, y int) int {
  21. if x < y {
  22. return y
  23. }
  24. return x
  25. }