Leetcode Note: Go - Best Time to Buy and Shell Stock
Best Time to Buy and Sell Stock - LeetCode
https://leetcode.com/problems/best-time-to-buy-and-sell-stock/
- Go 言語で取り組んだメモ
所感
- 株価の計算
- 後ろの要素との差分を計算して、より大きいものを導き出す
回答
100% simple golang solution - LeetCode Discuss
https://leetcode.com/problems/best-time-to-buy-and-sell-stock/discuss/283486/100-simple-golang-solution
func maxProfit(prices []int) int {
if len(prices) <= 1 {
return 0
}
min, maxSale := prices[0], 0
for _, price := range prices {
if price < min {
min = price
} else if (price-min) > maxSale {
maxSale = price-min
}
}
return maxSale
}
- 初期化
- min に prices[0] をセット
- max に 0 をセット
- prices を range でループ
- price が min より小さければ min を price で更新
- price - min が maxSale よりも大きければ maxSale を price - min で更新