Skip to content

Commit 6bff335

Browse files
authored
Merge pull request #24 from rihib/best_time_to_buy_and_sell_stock
Best Time to Buy and Sell Stock
2 parents c0ba25c + 0ebf208 commit 6bff335

File tree

2 files changed

+34
-0
lines changed

2 files changed

+34
-0
lines changed
Lines changed: 18 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,18 @@
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+
}
Lines changed: 16 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,16 @@
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+
}

0 commit comments

Comments
 (0)