Find Maximum Profit using Python

Finding the maximum profit while buying and selling stocks in the stock market is a great question for coding interviews at companies based on financial services. Here you are given an array of stock prices and transaction fees and what you have to do is calculate the maximum profitable amount. In this article, I will take you through how to find maximum profit using Python.

Find Maximum Profit: Problem Statement

Maximum Profit Finder is a good question for coding interviews. Here you are given an array or a list of stock prices of a particular day and an integer value that represents the transaction fees. Here you have to write an algorithm to find the maximum profit that you can achieve such that you can do as many transactions you want and you need to pay the transaction fees for each transaction that you do. Below is the problem statement that you get in the coding interviews to find the maximum profit.

You are given a list of stock prices of a particular day. You need to write an algorithm to find the maximum profit that you can achieve at most two transactions.

Find Maximum Profit using Python

Now let’s see how to solve the problem of finding maximum profit using the Python programming language. Here we have to take a recursive approach to solve this problem because first, we have to check if we have already bought stocks or not.

If we have already bought stocks then we can sell them at the current price including the transaction fees and if we do not have bought stocks then we can buy the stocks at the current price. Below is how to implement this strategy to find the maximum profit using Python:

Now let’s see how to implement the above algorithm to find the most profitable amount while buying or selling stocks with transaction fees:

profit = MaximumProfitFinder()
prices = [10, 20, 30, 40, 50]
print(profit.maximumProfit(prices, fees=15))
Output: 25

Summary

So this is how we can solve the problem of finding the most profitable amount while buying or selling stocks with a transaction fee. This is a good interview question at companies based on financial services. I hope you liked this article on how to find the maximum profit using Python. Feel free to ask your valuable questions in the comments section below.

Default image
Aman Kharwal

I am a programmer from India, and I am here to guide you with Data Science, Machine Learning, Python, and C++ for free. I hope you will learn a lot in your journey towards Coding, Machine Learning and Artificial Intelligence with me.

Leave a Reply

Data Science | Machine Learning | Python | C++ | Coding | Programming | JavaScript