当前位置:网站首页>Leetcode topic [array] - 121 - the best time to buy and sell stocks

Leetcode topic [array] - 121 - the best time to buy and sell stocks

2022-07-04 08:39:00 LabRat

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
}
原网站

版权声明
本文为[LabRat]所创,转载请带上原文链接,感谢
https://yzsam.com/2022/02/202202141443401129.html