122.go 812 B

1234567891011121314151617181920212223242526272829303132333435363738394041424344
  1. package main
  2. func maxProfitOld(prices []int) int {
  3. last, cost, profit := -1<<31, 1<<31-1, 0
  4. for _, v := range prices {
  5. if v < last {
  6. if last > cost {
  7. // sell stock
  8. profit += last - cost
  9. // buy stock
  10. cost = v
  11. }
  12. }
  13. if v < cost {
  14. // buy cheaper stock
  15. cost = v
  16. }
  17. // store price of yestoday
  18. last = v
  19. }
  20. // sell stock at last day
  21. if last > cost {
  22. profit += last - cost
  23. }
  24. return profit
  25. }
  26. // split into small pieces!
  27. // func maxProfit(prices []int) int {
  28. // profit := 0
  29. // for i := 1; i < len(prices); i++ {
  30. // if prices[i] > prices[i-1] {
  31. // profit += prices[i] - prices[i-1]
  32. // }
  33. // }
  34. // return profit
  35. // }
  36. // func main() {
  37. // a1 := []int{1, 2, 3, 46, 1, 4, 1, 4, 5}
  38. // a2 := []int{2, 1}
  39. // fmt.Println(maxProfit(a1))
  40. // fmt.Println(maxProfit(a2))
  41. // }