- Trending Categories
- Data Structure
- Networking
- RDBMS
- Operating System
- Java
- iOS
- HTML
- CSS
- Android
- Python
- C Programming
- C++
- C#
- MongoDB
- MySQL
- Javascript
- PHP

- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who

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:

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))

[2, 10, 4, 8], 3

6

- Related Questions & Answers
- Program to find maximum profit we can make by buying and selling stocks in Python?
- Maximum profit after buying and selling the stocks in C++
- Program to find maximum profit after buying and selling stocks at most two times in python
- Program to find maximum profit we can make by holding and selling profit in Python
- Maximum profit by buying and selling a share at most twice
- Program to find the maximum profit we can get by buying on stock market once in Python
- Program to find the maximum profit we can get by buying on stock market multiple times in Python
- Program to find maximum profit by selling diminishing-valued colored balls in Python
- Program to find maximum profit after cutting rods and selling same length rods in Python
- Program to get maximum profit by scheduling jobs in Python
- Program to find maximum profit we can make after k Buy and Sell in python
- Program to find maximum credit we can get by finishing some assignments in python
- Program to find maximum price we can get by holding items into a bag in Python
- Program to find maximum number of coins we can get using Python
- Program to find maximum score we can get in jump game in Python

Advertisements