Skip to content

Commit a18b740

Browse files
aQuaaQua
aQua
authored and
aQua
committed
121 finish
1 parent 773362c commit a18b740

File tree

2 files changed

+17
-5
lines changed

2 files changed

+17
-5
lines changed

Algorithms/0121.best-time-to-buy-and-sell-stock/best-time-to-buy-and-sell-stock.go

Lines changed: 8 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -2,11 +2,14 @@ package Problem0121
22

33
func maxProfit(prices []int) int {
44
max := 0
5-
for i, v := range prices {
6-
for j := i + 1; j < len(prices); j++ {
7-
if max < prices[j]-v {
8-
max = prices[j] - v
9-
}
5+
temp := 0
6+
for i := 1; i < len(prices); i++ {
7+
temp += prices[i] - prices[i-1]
8+
if temp < 0 {
9+
temp = 0
10+
}
11+
if max < temp {
12+
max = temp
1013
}
1114
}
1215

Algorithms/0121.best-time-to-buy-and-sell-stock/best-time-to-buy-and-sell-stock_test.go

Lines changed: 9 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -27,6 +27,15 @@ func Test_Problem0121(t *testing.T) {
2727

2828
qs := []question{
2929

30+
question{
31+
para{
32+
[]int{7, 2, 1, 5, 3, 6, 4},
33+
},
34+
ans{
35+
5,
36+
},
37+
},
38+
3039
question{
3140
para{
3241
[]int{7, 1, 5, 3, 6, 4},

0 commit comments

Comments
 (0)