121.E 买卖股票的最佳时机

Problem: 121. 买卖股票的最佳时机arrow-up-right

思路

要赚到最多的前,就要找到最大的波段,即不断寻找过往最低价与今天的股价之间的差值,使这个差值最大化。

Code

func maxProfit(prices []int) int {
	if len(prices) == 0 {
		return 0
	}

	profit := 0
	lowest := prices[0]
	for _, price := range prices {
		profit = max(profit, price-lowest)
		lowest = min(lowest, price)
	}

	return profit
}

func max(a, b int) int {
	if a > b {
		return a
	}

	return b
}

func min(a, b int) int {
	if a < b {
		return a
	}

	return b
}

Last updated