实现说明
买卖股票的最佳时机以函数 maxProfit、main为骨架。
迭代发生在 for _, price := range prices[1:] 内部——循环之外的语句只执行一遍。
使用要点
- 只跑在标准库上;没有要装的东西。
main的演示流程是maxProfit——跑一遍文件,这条流程从头到尾可见。
常见问题
「买卖股票的最佳时机」这个示例怎么运行?
把它当完整程序编译/解释运行即可——不需要先安装任何东西。
入口签名:func maxProfit(prices []int) int
核心语句
for _, price := range prices[1:] {
if price < lowest {
lowest = price
continue
}
if gain := price - lowest; gain > best {
best = gain
}
}
func main() {
fmt.Println(maxProfit([]int{7, 1, 5, 3, 6, 4}))
fmt.Println(maxProfit([]int{7, 6, 4, 3, 1}))
fmt.Println(maxProfit([]int{2, 4, 1}))
}
代码示例
package main
import "fmt"
// maxProfit: track the lowest buy price seen so far, sell later for max gain
func maxProfit(prices []int) int {
best := 0
lowest := prices[0]
for _, price := range prices[1:] {
if price < lowest {
lowest = price
continue
}
if gain := price - lowest; gain > best {
best = gain
}
}
return best
}
func main() {
fmt.Println(maxProfit([]int{7, 1, 5, 3, 6, 4}))
fmt.Println(maxProfit([]int{7, 6, 4, 3, 1}))
fmt.Println(maxProfit([]int{2, 4, 1}))
}