版权声明:原创勿转 https://cloud.tencent.com/developer/article/1412842
思路
一次遍历,同时记录最小价格和最大收益
code
代码语言:javascript复制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
}