Movatterモバイル変換


[0]ホーム

URL:


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

Commit028bd3e

Browse files
committed
Merge branch 'develop' of github.com:kylesliu/awesome-golang-leetcode into develop
2 parents361e61a +64ecb97 commit028bd3e

File tree

3 files changed

+77
-0
lines changed

3 files changed

+77
-0
lines changed
Lines changed: 38 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,38 @@
1+
#[122. Best Time to Buy and Sell Stock II][title]
2+
3+
##Description
4+
5+
Say you have an array for which the ith element is the price of a given stock on day i.
6+
7+
Design an algorithm to find the maximum profit. You may complete as many transactions as you like (i.e., buy one and sell one share of the stock multiple times).
8+
9+
10+
**Example 1:**
11+
12+
```
13+
Input: [7,1,5,3,6,4]
14+
Output: 7
15+
Explanation: Buy on day 2 (price = 1) and sell on day 3 (price = 5), profit = 5-1 = 4.
16+
Then buy on day 4 (price = 3) and sell on day 5 (price = 6), profit = 6-3 = 3.
17+
```
18+
19+
**Example 2:**
20+
21+
```
22+
Input: [1,2,3,4,5]
23+
Output: 4
24+
Explanation: Buy on day 1 (price = 1) and sell on day 5 (price = 5), profit = 5-1 = 4.
25+
Note that you cannot buy on day 1, buy on day 2 and sell them later, as you are
26+
engaging multiple transactions at the same time. You must sell before buying again.
27+
```
28+
29+
**Example 3:**
30+
31+
```
32+
Input: [7,6,4,3,1]
33+
Output: 0
34+
Explanation: In this case, no transaction is done, i.e. max profit = 0.
35+
```
36+
37+
38+
[title]:https://leetcode.com/problems/best-time-to-buy-and-sell-stock-ii/
Lines changed: 11 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,11 @@
1+
package Solution
2+
3+
funcmaxProfit(prices []int)int {
4+
maxProfit:=0
5+
fori:=0;i<len(prices)-1;i++ {
6+
ifprices[i]<prices[i+1] {
7+
maxProfit+= (prices[i+1]-prices[i])
8+
}
9+
}
10+
returnmaxProfit
11+
}
Lines changed: 28 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,28 @@
1+
package Solution
2+
3+
import (
4+
"reflect"
5+
"testing"
6+
)
7+
8+
funcTestMaxProfit(t*testing.T) {
9+
cases:= []struct {
10+
namestring
11+
inputs []int
12+
expectint
13+
}{
14+
{"TestCase 1", []int{7,1,5,3,6,4},7},
15+
{"TestCase 2", []int{1,2,3,4,5},4},
16+
{"TestCase 3", []int{7,6,4,3,1},0},
17+
}
18+
19+
for_,testcase:=rangecases {
20+
t.Run(testcase.name,func(t*testing.T) {
21+
got:=maxProfit(testcase.inputs)
22+
if!reflect.DeepEqual(got,testcase.expect) {
23+
t.Fatalf("expected: %v, but got %v, with inputs : %v",testcase.expect,got,testcase.inputs)
24+
}
25+
})
26+
}
27+
28+
}

0 commit comments

Comments
 (0)

[8]ページ先頭

©2009-2025 Movatter.jp