Interview Question
Share Lesson

# 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

Share:

1. 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.

2. The brute force solution is O(n2) but you can do better.

3. The optimal solution can solve this question in O(n) time and O(1) space where we only iterate through the input array once.

4. 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.

Share:

Test Results

Run your code and see results here...

### 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.

``Â ``