From 7e4755afa1c28a6d15f8bfdf1f847638d7809522 Mon Sep 17 00:00:00 2001 From: rihib Date: Sat, 31 Aug 2024 19:46:52 +0900 Subject: [PATCH] pullrequests/best_time_to_buy_and_sell_stock --- .../best_time_to_buy_and_sell_stock/step1.go | 18 ++++++++++++++++++ .../best_time_to_buy_and_sell_stock/step2.go | 16 ++++++++++++++++ 2 files changed, 34 insertions(+) create mode 100644 pullrequests/best_time_to_buy_and_sell_stock/step1.go create mode 100644 pullrequests/best_time_to_buy_and_sell_stock/step2.go diff --git a/pullrequests/best_time_to_buy_and_sell_stock/step1.go b/pullrequests/best_time_to_buy_and_sell_stock/step1.go new file mode 100644 index 0000000..ad300d9 --- /dev/null +++ b/pullrequests/best_time_to_buy_and_sell_stock/step1.go @@ -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 +} diff --git a/pullrequests/best_time_to_buy_and_sell_stock/step2.go b/pullrequests/best_time_to_buy_and_sell_stock/step2.go new file mode 100644 index 0000000..bb7f7c4 --- /dev/null +++ b/pullrequests/best_time_to_buy_and_sell_stock/step2.go @@ -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 +}