Skip to content

Commit 773362c

Browse files
aQuaaQua
aQua
authored and
aQua
committed
121 accepted
1 parent f5f2382 commit 773362c

File tree

3 files changed

+27
-9
lines changed

3 files changed

+27
-9
lines changed

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

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -4,19 +4,19 @@
44
Say you have an array for which the ith element is the price of a given stock on day i.
55

66
If you were only permitted to complete at most one transaction (ie, buy one and sell one share of the stock), design an algorithm to find the maximum profit.
7-
```
87
Example 1:
8+
```
99
Input: [7, 1, 5, 3, 6, 4]
1010
Output: 5
11-
```
1211
max. difference = 6-1 = 5 (not 7-1 = 6, as selling price needs to be larger than buying price)
1312
1413
```
1514
Example 2:
15+
```
1616
Input: [7, 6, 4, 3, 1]
1717
Output: 0
18-
```
1918
In this case, no transaction is done, i.e. max profit = 0.
19+
```
2020

2121
## 解题思路
2222

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

33
func maxProfit(prices []int) int {
4+
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+
}
10+
}
11+
}
412

13+
return max
514
}

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

Lines changed: 15 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -1,8 +1,8 @@
11
package Problem0121
22

33
import (
4-
"testing"
54
"fmt"
5+
"testing"
66

77
"github.com/stretchr/testify/assert"
88
)
@@ -19,7 +19,7 @@ type para struct {
1919

2020
// ans 是答案
2121
type ans struct {
22-
one int
22+
one int
2323
}
2424

2525
func Test_Problem0121(t *testing.T) {
@@ -29,20 +29,29 @@ func Test_Problem0121(t *testing.T) {
2929

3030
question{
3131
para{
32-
,
32+
[]int{7, 1, 5, 3, 6, 4},
33+
},
34+
ans{
35+
5,
36+
},
37+
},
38+
39+
question{
40+
para{
41+
[]int{7, 6, 5, 4, 3, 2, 1},
3342
},
3443
ans{
35-
,
44+
0,
3645
},
3746
},
38-
47+
3948
// 如需多个测试,可以复制上方元素。
4049
}
4150

4251
for _, q := range qs {
4352
a, p := q.ans, q.para
4453
fmt.Printf("~~%v~~\n", p)
4554

46-
ast.Equal(a.one, maxProfit(p.prices ), "输入:%v", p)
55+
ast.Equal(a.one, maxProfit(p.prices), "输入:%v", p)
4756
}
4857
}

0 commit comments

Comments
 (0)