-
Notifications
You must be signed in to change notification settings - Fork 32
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
- Loading branch information
Showing
3 changed files
with
62 additions
and
0 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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 | ||
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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) | ||
} | ||
} | ||
} |