Skip to content

Instantly share code, notes, and snippets.

@RobAWilkinson
Created June 22, 2015 14:39
Show Gist options
  • Save RobAWilkinson/bb39cbd92ada2255e704 to your computer and use it in GitHub Desktop.
Save RobAWilkinson/bb39cbd92ada2255e704 to your computer and use it in GitHub Desktop.
/**
* I have an array stock_prices_yesterday where:
*
* - The indices are the time in minutes past trade opening time, which was 9:30am local time
* - The values are the prices in dollars of Apple stock at the time
*
* For example, the stock cost $500 at 10:30am, so stock_prices_yesterday[60] = 500;
*
* Write an efficient algorithm for computing the best profit I could have made from 1 purchase
* and 1 sale of 1 Apple stock yesterday
*
*/
var apple = [1000, 200, 800, 1100, 400, 1400];
var min = apple.shift();
function bestProfit(stock_prices_yesterday) {
var minValue = stock_prices_yesterday.shift();
var maxProfit = 0;
for(var i = 0; i < stock_prices_yesterday.length; i++) {
if(stock_prices_yesterday[i] < minValue) {
minValue = stock_prices_yesterday[i];
}
if ( stock_prices_yesterday[i] > minValue ) {
if(stock_prices_yesterday[i] - minValue > maxProfit) {
maxProfit = stock_prices_yesterday[i] - minValue;
}
}
}
return maxProfit;
}
console.log(bestProfit(apple));
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment