Program to find maximum profit we can get by buying and selling stocks with a fee in Python?

PythonServer Side ProgrammingProgramming

Suppose we have a list of stock prices of a company in chronological sequence, and also have the transaction fee for one sell transaction. We have to find the maximum profit we could have made from buying and selling that stock any number of times. We must buy before we can sell it.

So, if the input is like prices = [2, 10, 4, 8] fee = 3, then the output will be 6, as we can buy at 2 and sell at 10 and incur a fee of 3, so profit is 5. Then we buy at 4 and sell at 8 and incur a fee of 3, so profit 1, total profit 6.

To solve this, we will follow these steps:

  • n := size of prices

  • Define a function recur() . This will take i:= 0 and flag := 0

  • if i is same as n, then

    • return 0

  • if flag is false, then

    • return maximum of recur(i + 1, 1) - prices[i] and recur(i + 1, 0)

  • return maximum of recur(i + 1, 1) and recur(i + 1, 0) + prices[i] - fee

  • From the main method call recur()

Let us see the following implementation to get better understanding:

Example

 Live Demo

class Solution:
   def solve(self, prices, fee):
      n = len(prices)

      def recur(i=0, flag=0):
         if i == n:
            return 0
         if not flag:
            return max(recur(i + 1, 1) - prices[i], recur(i + 1, 0))
         return max(recur(i + 1, 1), recur(i + 1, 0) + prices[i] - fee)

      return recur()

ob = Solution()
prices = [2, 10, 4, 8]
fee = 3
print(ob.solve(prices, fee))

Input

[2, 10, 4, 8], 3

Output

6
raja
Published on 10-Nov-2020 08:05:39
Advertisements