思路
一次遍历,同时记录最小价格和最大收益
code
func maxProfit(prices []int) int {
maxProfit := 0
minPrice := math.MaxInt64
for _, v := range prices {
minPrice = mymin(minPrice, v)
maxProfit = mymax(maxProfit, v-minPrice)
}
return maxProfit
}
func mymin(x, y int) int {
if x > y {
return y
}
return x
}
func mymax(x, y int) int {
if x > y {
return x
}
return y
}
更多内容请移步我的repo:https://github.com/anakin/golang-leetcode