File tree Expand file tree Collapse file tree 2 files changed +34
-0
lines changed
pullrequests/best_time_to_buy_and_sell_stock Expand file tree Collapse file tree 2 files changed +34
-0
lines changed Original file line number Diff line number Diff line change
1
+ //lint:file-ignore U1000 Ignore all unused code
2
+ package besttimetobuyandsellstock
3
+
4
+ /*
5
+ 時間:4分30秒
6
+
7
+ 走査している中で現在の値に対して最大の利益を取り得るのは今まで走査してきた中の最小値であるため、最小値を更新した後に、現在の値に対する利益を計算し、それが最大値であれば更新するようにしている。
8
+
9
+ 解いた後に中の変数名と関数名が一緒になってしまっていることに気づいた。
10
+ */
11
+ func maxProfitStep1 (prices []int ) int {
12
+ minPrice , maxValue := prices [0 ], 0
13
+ for _ , price := range prices {
14
+ minPrice = min (minPrice , price )
15
+ maxValue = max (maxValue , price - minPrice )
16
+ }
17
+ return maxValue
18
+ }
Original file line number Diff line number Diff line change
1
+ //lint:file-ignore U1000 Ignore all unused code
2
+ package besttimetobuyandsellstock
3
+
4
+ import "math"
5
+
6
+ /*
7
+ 関数名と被らないように変数名を更新したのと、minPriceをmath.MaxIntで初期化することで、たとえ空の入力が渡されたとしてもエラーにならないようにした。
8
+ */
9
+ func maxProfit (prices []int ) int {
10
+ minPrice , maxValue := math .MaxInt , 0
11
+ for _ , price := range prices {
12
+ minPrice = min (minPrice , price )
13
+ maxValue = max (maxValue , price - minPrice )
14
+ }
15
+ return maxValue
16
+ }
You can’t perform that action at this time.
0 commit comments