# 算法-买卖股票的最佳时机(121)

Gabriel

#### 买卖股票的最佳时机(122)

``````输入: [7,1,5,3,6,4]

注意利润不能是 7-1 = 6, 因为卖出价格需要大于买入价格；同时，你不能在买入前卖出股票。

``````package main

import "fmt"

func main() {
prices  := []int{2,3,4,54,1,10000}
maxProfit := maxProfit(prices)
fmt.Println(maxProfit)

}

func maxProfit(prices []int) int {
maxProfit := 0 // 哨兵值
for i:=0;i<len(prices) - 1;i++ {
// 双层循环  prices[0] 买入 然后和 price[1],price[2]... 相减，求每次循环的最大值
for j:=i+1;j<len(prices);j++ {

if prices[j] - prices[i] > maxProfit && prices[j] - prices[i] >= 0 {
maxProfit = prices[j] - prices[i]
}
}
}
return maxProfit
}``````

`````` panic: runtime error: index out of range [0] with length 0
main.maxProfit(0x5d5f70, 0x0, 0x0, 0x4cf400)
solution.go, line 6
main.__helper__(...)
solution.go, line 32
main.main()
solution.go, line 60
``````

``````if len(prices) <= 0 {
return 0
}
``````
``````package main

import "fmt"

func main() {
prices  := []int{2,3,4,54,1,10000}
maxProfit := maxProfit(prices)
fmt.Println(maxProfit)

}

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

maxValue := 0
minValue := prices[0]

for i := 1;i<len(prices);i++ {
maxValue = max(maxValue,prices[i] - minValue)
minValue = min(minValue,prices[i])
}
return maxValue
}

func max(i,j int ) int {
if i > j {
return i
}
return j
}

func min(i,j int ) int {
if i > j {
return j
}
return i
}``````

24 声望
2 粉丝