121.go 409 B

123456789101112131415161718192021222324252627
  1. package main
  2. import (
  3. "fmt"
  4. )
  5. func maxProfit(prices []int) int {
  6. cost, profit := 1<<31-1, 0
  7. for _, v := range prices {
  8. if v < cost {
  9. cost = v
  10. }
  11. if v-cost > profit {
  12. profit = v - cost
  13. }
  14. }
  15. return profit
  16. }
  17. func main() {
  18. a1 := []int{1, 2, 3, 4, 5}
  19. a2 := []int{5, 4, 3, 2, 1}
  20. a3 := []int{7, 4, 3, 8, 1}
  21. fmt.Println(maxProfit(a1))
  22. fmt.Println(maxProfit(a2))
  23. fmt.Println(maxProfit(a3))
  24. }