Skip to content

Commit

Permalink
Merge f40edcf into bb91eec
Browse files Browse the repository at this point in the history
  • Loading branch information
vaskoz committed Jan 1, 2020
2 parents bb91eec + f40edcf commit 70ce47a
Show file tree
Hide file tree
Showing 3 changed files with 61 additions and 0 deletions.
1 change: 1 addition & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -405,4 +405,5 @@ problems from
* [Day 405](https://github.com/vaskoz/dailycodingproblem-go/issues/819)
* [Day 406](https://github.com/vaskoz/dailycodingproblem-go/issues/821)
* [Day 407](https://github.com/vaskoz/dailycodingproblem-go/issues/823)
* [Day 408](https://github.com/vaskoz/dailycodingproblem-go/issues/825)

29 changes: 29 additions & 0 deletions day408/problem.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,29 @@
package day408

// MaxProfit returns the maximum possible profit given
// exactly 'k' buy/sell pairs.
// Runs in O(N*k) time and O(N*k) space.
func MaxProfit(prices []int, k int) int {
profits := make([][]int, k+1)
for i := range profits {
profits[i] = make([]int, len(prices)+1)
}

for i := 1; i <= k; i++ {
diff := -int(^uint(0)>>1) - 1
for j := 1; j < len(prices); j++ {
diff = max(diff, profits[i-1][j-1]-prices[j-1])
profits[i][j] = max(profits[i][j-1], prices[j]+diff)
}
}

return profits[k][len(prices)-1]
}

func max(a, b int) int {
if a > b {
return a
}

return b
}
31 changes: 31 additions & 0 deletions day408/problem_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,31 @@
package day408

import "testing"

// nolint
var testcases = []struct {
prices []int
k int
maxProfit int
}{
{[]int{5, 2, 4, 0, 1}, 2, 3},
{[]int{12, 14, 17, 10, 14, 13, 12, 15}, 3, 12},
}

func TestMaxProfit(t *testing.T) {
t.Parallel()

for _, tc := range testcases {
if maxProfit := MaxProfit(tc.prices, tc.k); maxProfit != tc.maxProfit {
t.Errorf("Expected %v got %v", tc.maxProfit, maxProfit)
}
}
}

func BenchmarkMaxProfit(b *testing.B) {
for i := 0; i < b.N; i++ {
for _, tc := range testcases {
MaxProfit(tc.prices, tc.k)
}
}
}

0 comments on commit 70ce47a

Please sign in to comment.