Created
June 22, 2015 14:39
-
-
Save RobAWilkinson/bb39cbd92ada2255e704 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* 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