Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
38 changes: 38 additions & 0 deletions src/0122.Best-Time-To-Buy-And-Sell-Stock-II/README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,38 @@
# [122. Best Time to Buy and Sell Stock II][title]

## Description

Say you have an array for which the ith element is the price of a given stock on day i.

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).


**Example 1:**

```
Input: [7,1,5,3,6,4]
Output: 7
Explanation: Buy on day 2 (price = 1) and sell on day 3 (price = 5), profit = 5-1 = 4.
Then buy on day 4 (price = 3) and sell on day 5 (price = 6), profit = 6-3 = 3.
```

**Example 2:**

```
Input: [1,2,3,4,5]
Output: 4
Explanation: Buy on day 1 (price = 1) and sell on day 5 (price = 5), profit = 5-1 = 4.
Note that you cannot buy on day 1, buy on day 2 and sell them later, as you are
engaging multiple transactions at the same time. You must sell before buying again.
```

**Example 3:**

```
Input: [7,6,4,3,1]
Output: 0
Explanation: In this case, no transaction is done, i.e. max profit = 0.
```


[title]: https://leetcode.com/problems/best-time-to-buy-and-sell-stock-ii/
11 changes: 11 additions & 0 deletions src/0122.Best-Time-To-Buy-And-Sell-Stock-II/Solution.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,11 @@
package Solution

func maxProfit(prices []int) int {
maxProfit := 0
for i := 0; i < len(prices)-1; i++ {
if prices[i] < prices[i+1] {
maxProfit += (prices[i+1] - prices[i])
}
}
return maxProfit
}
28 changes: 28 additions & 0 deletions src/0122.Best-Time-To-Buy-And-Sell-Stock-II/Solution_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,28 @@
package Solution

import (
"reflect"
"testing"
)

func TestMaxProfit(t *testing.T) {
cases := []struct {
name string
inputs []int
expect int
}{
{"TestCase 1", []int{7, 1, 5, 3, 6, 4}, 7},
{"TestCase 2", []int{1, 2, 3, 4, 5}, 4},
{"TestCase 3", []int{7, 6, 4, 3, 1}, 0},
}

for _, testcase := range cases {
t.Run(testcase.name, func(t *testing.T) {
got := maxProfit(testcase.inputs)
if !reflect.DeepEqual(got, testcase.expect) {
t.Fatalf("expected: %v, but got %v, with inputs : %v", testcase.expect, got, testcase.inputs)
}
})
}

}