Finding the best time to buy and sell stocks is one of the popular coding interview questions. Here we need to return the maximum profit we can achieve from buying and selling a stock. So, if you want to learn how to maximize profit from buying and selling stocks, this article is for you. In this article, I will take you through how to find the best time to buy and sell stock using Python.
Best Time to Buy and Sell Stock using Python
The problem of finding the best time to buy and sell a stock is also known as a maximum profit finder. Here we will be given an array of closing stock prices on different days, and we need to frame a solution by choosing a single day to buy a stock and choosing another day to sell that stock in the future to maximize our profit.
For example, have a look at the input and output of this problem below:
Input: prices = [7, 1, 5, 3, 6, 4]
Output = 5
In the example above, the stock price is 7 on the first day. We bought the stock on day 2 at a price of 1 and sold it on day 5 at a price of 6. Hence profit = 5 (6 – 1).
Now below is how we can find the best time to buy and sell stock using the Python programming language:
def maxProfit(prices): buy = 0 sell = 1 max_profit = 0 while sell < len(prices): if prices[sell] > prices[buy]: profit = prices[sell] - prices[buy] max_profit = max(profit, max_profit) else: buy = sell sell = sell + 1 return max_profit prices = [7,1,5,3,6,4] print(maxProfit(prices))
Output: 5
I hope you now have understood how to solve the problem of finding the best time to buy and sell stock using Python. You can find many more practice questions to improve your problem-solving skills using Python here.
Summary
The problem of finding the best time for buying and selling a stock is also known as a maximum profit finder. Here we will be given an array of closing stock prices on different days, and we need to frame a solution by choosing a single day to buy a stock and choosing another day to sell that stock in the future to maximize our profit. I hope you liked this article on finding the best time for buying and selling stock using Python. Feel free to ask valuable questions in the comments section below.