|
| 1 | +############################# |
| 2 | +# Author: yash kesharwani |
| 3 | +# File: best_time_to_buy_sell_stock.py |
| 4 | +# comments: This program output the |
| 5 | +# best time to buy and sell stock with fees |
| 6 | +############################# |
| 7 | +import doctest |
| 8 | + |
| 9 | + |
| 10 | +class Solution: |
| 11 | + def solve(self, prices, index, fee, buy, dp): |
| 12 | + if index >= len(prices): |
| 13 | + return 0 |
| 14 | + if dp[index][buy] != -1: |
| 15 | + return dp[index][buy] |
| 16 | + |
| 17 | + profit = 0 |
| 18 | + if buy == 1: |
| 19 | + profit = max( |
| 20 | + -prices[index] + self.solve(prices, index + 1, fee, 0, dp), |
| 21 | + self.solve(prices, index + 1, fee, 1, dp), |
| 22 | + ) |
| 23 | + else: |
| 24 | + profit = max( |
| 25 | + (prices[index] + self.solve(prices, index + 1, fee, 1, dp)) - fee, |
| 26 | + self.solve(prices, index + 1, fee, 0, dp), |
| 27 | + ) |
| 28 | + |
| 29 | + dp[index][buy] = profit |
| 30 | + return profit |
| 31 | + |
| 32 | + def maxprofit(self, prices, fee): |
| 33 | + n = len(prices) |
| 34 | + dp = [[-1] * 2 for _ in range(n)] |
| 35 | + |
| 36 | + return self.solve(prices, 0, fee, 1, dp) |
| 37 | + |
| 38 | + |
| 39 | +def main(): |
| 40 | + ## This is the function for taking input and output ## |
| 41 | + prices = list(map(int, input("Enter the list of prices: ").split())) |
| 42 | + fee = int(input("Enter the transaction fee: ")) |
| 43 | + |
| 44 | + s = Solution() |
| 45 | + max_profit = s.maxprofit(prices, fee) |
| 46 | + |
| 47 | + print("Maximum profit:", max_profit) |
| 48 | + |
| 49 | + |
| 50 | +if __name__ == "__main__": |
| 51 | + doctest.testmod() |
| 52 | + main() |
0 commit comments