Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
18 changes: 18 additions & 0 deletions pullrequests/best_time_to_buy_and_sell_stock/step1.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,18 @@
//lint:file-ignore U1000 Ignore all unused code
package besttimetobuyandsellstock

/*
時間:4分30秒

走査している中で現在の値に対して最大の利益を取り得るのは今まで走査してきた中の最小値であるため、最小値を更新した後に、現在の値に対する利益を計算し、それが最大値であれば更新するようにしている。

解いた後に中の変数名と関数名が一緒になってしまっていることに気づいた。
*/
func maxProfitStep1(prices []int) int {
minPrice, maxValue := prices[0], 0
for _, price := range prices {
minPrice = min(minPrice, price)
maxValue = max(maxValue, price-minPrice)
}
return maxValue
}
16 changes: 16 additions & 0 deletions pullrequests/best_time_to_buy_and_sell_stock/step2.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,16 @@
//lint:file-ignore U1000 Ignore all unused code
package besttimetobuyandsellstock

import "math"

/*
関数名と被らないように変数名を更新したのと、minPriceをmath.MaxIntで初期化することで、たとえ空の入力が渡されたとしてもエラーにならないようにした。
*/
func maxProfit(prices []int) int {
minPrice, maxValue := math.MaxInt, 0
for _, price := range prices {
minPrice = min(minPrice, price)
maxValue = max(maxValue, price-minPrice)
}
return maxValue
}