Leetcode Golang 121. Best Time to Buy and Sell Stock.go

2019-04-12 10:21:32 浏览数 (1)

版权声明:原创勿转 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
}

0 人点赞