Writing interview questions hasn't made me rich. Maybe trading Apple stocks will.
I have an array stockPricesYesterday where the keys are the number of minutes into the day (starting with midnight) and the values are the price of Apple stock at that time. For example, the stock cost $500 at 1am, so stockPricesYesterday = 500.
Write an efficient algorithm for computing the best profit I could have made from 1 purchase and 1 sale of an Apple stock yesterday.
It is not sufficient to simply take the difference between the highest price and the lowest price, because the highest price may come before the lowest price. You must buy before you sell.
You can do this in time.
The brute force approach would be to try every pair of times (treating the earlier time as the buy time and the later time as the sell time) and see which one is best. There are n^2 such combinations, so this will take time. We can do better.
If we're going to do better than , we're probably going to do it in either or . comes up in sorting and searching algorithms where we're recursively cutting the set in half. It's not obvious that we can save time by cutting the set in half here. Let's first see how well we can do by looping through the set only once (this costs only time).
Since we're going to loop through the set only once, let's use a greedy approach, where we keep a running max_profit until we reach the end. We'll start our max profit at $0. As we're iterating, how do we know if we've found a new max profit?
At each iteration, our max_profit is either:
the same as the max_profit at the last time step, or
the best profit we can get by selling at the current_price
How do we know when we have case (2)?
The best profit we can get by selling at the current_price is simply the difference between the current_price and the min_price to the left of it. If this difference is greater than the current max_profit, we have a new max_profit.
We walk through the array from beginning to end, keeping track of:
our min_price so far
our max_profit so far
For each time, we check to see if:
we have a new min_price, or
buying at the current min_price and selling at the current_price would give a new max_profit.
So we have:
min_price = stockPricesYesterday
max_profit = 0
for time in range(len(stockPricesYesterday)):
current_price = stockPricesYesterday[time]
min_price = min(min_price, current_price)
max_profit = max(max_profit, current_price - min_price)
time (we're only looping through the array once) and space.