Skip to content

Commit

Permalink
Merge 98999af into 0e7f631
Browse files Browse the repository at this point in the history
  • Loading branch information
vaskoz committed Jan 8, 2020
2 parents 0e7f631 + 98999af commit d20ba52
Show file tree
Hide file tree
Showing 3 changed files with 62 additions and 0 deletions.
1 change: 1 addition & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -411,4 +411,5 @@ problems from
* [Day 412](https://github.com/vaskoz/dailycodingproblem-go/issues/832)
* [Day 413](https://github.com/vaskoz/dailycodingproblem-go/issues/834)
* [Day 414](https://github.com/vaskoz/dailycodingproblem-go/issues/836)
* [Day 415](https://github.com/vaskoz/dailycodingproblem-go/issues/838)

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

// MaxProfitWithFee returns the maximum possible profit
// by making transactions where each one has a fee.
// A backtracking algorithm that tries all profitable paths
// looking for the most profitable.
func MaxProfitWithFee(prices []int, fee int) int {
if len(prices) < 2 {
return 0
}

buy := prices[0]

var maxProfit int

for i := 1; i < len(prices); i++ {
if prices[i] > buy+fee {
thisTradeProfit := prices[i] - buy - fee
totalProfit := thisTradeProfit + MaxProfitWithFee(prices[i+1:], fee)

if totalProfit > maxProfit {
maxProfit = totalProfit
}
}
}

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

import (
"reflect"
"testing"
)

// nolint
var testcases = []struct {
prices []int
fee int
maxProfit int
}{
{[]int{1, 3, 2, 8, 4, 10}, 2, 9},
}

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

for _, tc := range testcases {
if result := MaxProfitWithFee(tc.prices, tc.fee); !reflect.DeepEqual(tc.maxProfit, result) {
t.Errorf("Expected %v, got %v", tc.maxProfit, result)
}
}
}

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

0 comments on commit d20ba52

Please sign in to comment.