1234567891011121314151617181920212223242526272829303132333435363738394041424344 |
- package main
- func maxProfitOld(prices []int) int {
- last, cost, profit := -1<<31, 1<<31-1, 0
- for _, v := range prices {
- if v < last {
- if last > cost {
- // sell stock
- profit += last - cost
- // buy stock
- cost = v
- }
- }
- if v < cost {
- // buy cheaper stock
- cost = v
- }
- // store price of yestoday
- last = v
- }
- // sell stock at last day
- if last > cost {
- profit += last - cost
- }
- return profit
- }
- // split into small pieces!
- // func maxProfit(prices []int) int {
- // profit := 0
- // for i := 1; i < len(prices); i++ {
- // if prices[i] > prices[i-1] {
- // profit += prices[i] - prices[i-1]
- // }
- // }
- // return profit
- // }
- // func main() {
- // a1 := []int{1, 2, 3, 46, 1, 4, 1, 4, 5}
- // a2 := []int{2, 1}
- // fmt.Println(maxProfit(a1))
- // fmt.Println(maxProfit(a2))
- // }
|