剑指 Offer 63. 股票的最大利润

剑指 Offer 63. 股票的最大利润

https://leetcode-cn.com/problems/gu-piao-de-zui-da-li-run-lcof/

类似与 最大子数组和,不需要关心买入状态。由于只能买卖一次,只需要知道当前第 n 天,是今天卖出利润高,或是前 n - 1 天的利润高。如果是今天卖出,就要知道前 n - 1 天中的最小价格,用一个变量记录即可。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
func maxProfit(prices []int) int {
n := len(prices)
if n == 0 {
return 0
}
pastMax := 0
min := prices[0]

for i := 1; i < n; i++ {
pastMax = max(pastMax, prices[i] - min)
if prices[i] < min {
min = prices[i]
}
}

return pastMax
}

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