122.go 786 B

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