Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

Commit 402ac63

Browse files
author
Sandy
authored
Merge pull request #193 from openset/develop
Add: Best Time to Buy and Sell Stock
2 parents 67c0023 + 4113aea commit 402ac63

File tree

2 files changed

+46
-0
lines changed

2 files changed

+46
-0
lines changed
Lines changed: 12 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1 +1,13 @@
11
package best_time_to_buy_and_sell_stock
2+
3+
func maxProfit(prices []int) int {
4+
ans, min := 0, 0
5+
for i, v := range prices {
6+
if v < prices[min] {
7+
min = i
8+
} else if v-prices[min] > ans {
9+
ans = v - prices[min]
10+
}
11+
}
12+
return ans
13+
}
Lines changed: 34 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1 +1,35 @@
11
package best_time_to_buy_and_sell_stock
2+
3+
import "testing"
4+
5+
type caseType struct {
6+
input []int
7+
expected int
8+
}
9+
10+
func TestMaxProfit(t *testing.T) {
11+
tests := [...]caseType{
12+
{
13+
input: []int{7, 1, 5, 3, 6, 4},
14+
expected: 5,
15+
},
16+
{
17+
input: []int{7, 6, 4, 3, 1},
18+
expected: 0,
19+
},
20+
{
21+
input: []int{1, 1, 1, 1, 1},
22+
expected: 0,
23+
},
24+
{
25+
input: []int{},
26+
expected: 0,
27+
},
28+
}
29+
for _, tc := range tests {
30+
output := maxProfit(tc.input)
31+
if output != tc.expected {
32+
t.Fatalf("input: %v, output: %v, expected: %v", tc.input, output, tc.expected)
33+
}
34+
}
35+
}

0 commit comments

Comments
(0)

AltStyle によって変換されたページ (->オリジナル) /