Skip to content

Commit 64ecb97

Browse files
authored
Merge pull request 6boris#51 from hiepndd/develop
Add solution problem 0122
2 parents e6e59c6 + 8912022 commit 64ecb97

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+
func maxProfit(prices []int) int {
4+
maxProfit := 0
5+
for i := 0; i < len(prices)-1; i++ {
6+
if prices[i] < prices[i+1] {
7+
maxProfit += (prices[i+1] - prices[i])
8+
}
9+
}
10+
return maxProfit
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+
func TestMaxProfit(t *testing.T) {
9+
cases := []struct {
10+
name string
11+
inputs []int
12+
expect int
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 := range cases {
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)