# Best Time to Buy and Sell Stock

You start day trading while working as a remote software engineer, and you realize that you may have found a strategy that will allow you to make tons of money by going against hedge funds. You realize this strategy will require you to hodl for multiple days to realize the largest profit, so you know that you will need diamond hands ðŸ’ŽðŸ™Œ. In order to backtest this strategy, you want to see the maximum you could have earned by buying at the lowest point and selling at the highest point.

**Write a function getMaxProfit that takes an array of stock prices ordered sequentially by day and returns the max profit you could earn by buying and selling at the optimal time.**

**You never want to lose money, so if there is no max profit, return 0.**

Since these are stock prices, we will assume the items in the array will all be positive integers.

`Â `

## Breakdown

### Validate My Answer

You may be tempted to find the difference between the smallest and largest value in the input stock price array. Since these prices are listed sequentially by day, this solution may produce results where you buy in the future and sell in the past. This is impossible, at least until we invent time travel.

The brute force solution is

*O(n*but you can do better.^{2})The optimal solution can solve this question in

*O(n)*time and*O(1)*space where we only iterate through the input array once.This question has many edge cases, so make sure you handle those. For example: prices always decreasing, prices always increasing, empty input array, single price input array, etc.

### Best Time to Buy and Sell Stock

You start day trading while working as a remote software engineer, and you realize that you may have found a strategy that will allow you to make tons of money by going against hedge funds. You realize this strategy will require you to hodl for multiple days to realize the largest profit, so you know that you will need diamond hands ðŸ’ŽðŸ™Œ. In order to backtest this strategy, you want to see the maximum you could have earned by buying at the lowest point and selling at the highest point.

**Write a function getMaxProfit that takes an array of stock prices ordered sequentially by day and returns the max profit you could earn by buying and selling at the optimal time.**

**You never want to lose money, so if there is no max profit, return 0.**

Since these are stock prices, we will assume the items in the array will all be positive integers.

`Â `