Force link :https://leetcode-cn.com/probl...
Their thinking :
1、 This topic can be used Greedy Algorithm To solve the problem , Greedy algorithm is an algorithm to find the local optimal solution of the problem with non aftereffect .
2、 Greedy strategy : When buying and selling stocks , We know that the most profitable thing is to buy at the lowest point , Then sell at the peak . So we record a lowest price , Then record a maximum profit , The price is constantly updated when traversing from front to back , Until you get the maximum profit
func maxProfit(prices []int) int {
max := 0
minPrice := prices[0]
for i := 1; i < len(prices); i++ {
if minPrice > prices[i] {
minPrice = prices[i]
}
if prices[i] - minPrice > max {
max = prices[i] - minPrice
}
}
return max
}