
QUESTION:
- Write a programming interview question of:
How much money could I have made yesterday if I had been trading Apple stocks all day?
I grabbed Apple’s stock prices from yesterday and put them in a list called stock_prices
, where:
- The indices are the time in minutes past trade opening time, which was 9:30AM local time.
- The values are the price in US Dollars of one share of Apple stock at that time.
If the stock cost $500 at 10:30AM that means that the stock_prices[60] = 500.
Now, write an efficient function that takes stock_prices
and returns the best profit I could have made from the one purchase and one sale of one share of Apple stock yesterday.
SOLUTION:
stock_prices = [10,7,5,8,11,9] get_max_profit(stock_prices)
# Returns 6 buying for $5 and selling for $11
There is no “shorting” you need to buy before you can sell. You can also not buy and sell in the same time step, you have to wait for 1 minute to pass.
You cannot just take the differences between the highest and the lowest price. This is because the highest price might come before the lowest price and you have to buy before you can sell.
If the price goes down all day, the profit will be negative.
You can do this in O(n) time and O(1) space.
So, first you will need to write the an example value for stock_prices
and then find the maximum profit. How do you figure out the maximum profit?
Using the brute force approach, you will be able to try every pair of times treating the earlier time as the buy time and the later time as the sell time, then check which among the time is higher.
def get_max_profit(stock_prices): max_profit = 0
# Go throuth every time
for outer_time in range(len(stock_prices)):
# For every time, go through every other time
for inner_time in range(len(stock_prices)):
# For each pair, find the earlier and later times
earlier_time = min(outer_time, inner_time)
later_time = max(outer_time, inner_time)
# And use those to find the earlier and the later prices
earlier_price = stock_prices[earlier_time]
later_price = stock_prices[later_time]
# See what our profit would be if we bought at the
# earlier price and sold at the later price
potential_profit = later_price - earlier_price
# Update max_profit if we can do better
max_profit = max(max_profit, potential_profit)
return max_profit
Continuation on Part 2…
If you have any question or comment, do not hesitate to ask us.
Quote: The moon looks upon many night flowers; the night flowers see but one moon. – Jean Ingelow