Apple Stocks (Practice Interview Question) - Interview Cake
Apple Stocks (Practice Interview Question) - Interview Cake
So I grabbed Apple's stock prices from yesterday and put them in an array called
stockPrices, 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.
Write an ef cient function that takes stockPrices and returns the best pro t I could
have made from one purchase and one sale of one share of Apple stock
yesterday.
For example:
JavaScript
const stockPrices = [10, 7, 5, 8, 11, 9];
getMaxProfit(stockPrices);
// Returns 6 (buying for $5 and selling for $11)
No "shorting"—you need to buy before you can sell. Also, you can't buy and sell in the
same time step—at least 1 minute has to pass.
Breakdown
To start, try writing an example value for stockPrices and nding the maximum pro t "by hand."
What's your process for guring out the maximum pro t?
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 higher.
JavaScript
function getMaxProfit(stockPrices) {
let maxProfit = 0;
return maxProfit;
But that will take O(n2 ) time,↴ since we have two nested loops—for every time, we're going
through every other time. Also, it's not correct: we won't ever report a negative pro t! Can we do
better?