# 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):
sell = 1
max_profit = 0
while sell < len(prices):
max_profit = max(profit, max_profit)
else:
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.

##### Aman Kharwal

I'm a writer and data scientist on a mission to educate others about the incredible power of dataðŸ“ˆ.

Articles:Â 1370