majianyu
3/11/2019 - 5:40 PM

121 买卖股票的最佳时机

* 设置 res 变量为0

  • 设置买入变量 low 为极大数
  • 遍历数组, diff 当前元素减 low
  • 如果 diff > res , res = diff
  • 如果 diff <= 0 ,说明当前元素买入价更低,更新 low
func maxProfit(prices []int) int {
	res := 0
	low := 1<<31 - 1
	for i := 0; i < len(prices); i++ {
		diff := prices[i] - low
		if diff > res {
			res = diff
		}
		if diff <= 0 {
			low = prices[i]
		}
	}
	return res
}