Skip to content

Instantly share code, notes, and snippets.

@jessemillar
Last active September 11, 2016 22:16
Show Gist options
  • Save jessemillar/babb214bacc498fc22743aeff707c5b3 to your computer and use it in GitHub Desktop.
Save jessemillar/babb214bacc498fc22743aeff707c5b3 to your computer and use it in GitHub Desktop.
// https://www.interviewcake.com/question/javascript/stock-price
function getMaxProfit(stockPrices) {
var lowestPrice = stockPrices[0];
var maxProfit = stockPrices[1] - lowestPrice;
for (var i = 1; i < stockPrices.length; i++) {
var difference = stockPrices[i] - lowestPrice;
if (difference > maxProfit) {
maxProfit = difference;
}
if (stockPrices[i] < lowestPrice) {
lowestPrice = stockPrices[i];
}
}
return maxProfit;
}
function debug(message) {
console.log("DEBUG: " + message);
}
var genericPrices = [10, 7, 5, 8, 11, 9];
var negativePrices = [10, 9, 5, 3, 1, 0];
console.log(getMaxProfit(negativePrices));
@jessemillar
Copy link
Author

jessemillar commented Sep 11, 2016

Currently has an O(n^2) complexity which isn't great...

@jessemillar
Copy link
Author

Now accounts for negative values being the best return on investment.

@jessemillar
Copy link
Author

Now with O(n) complexity and O(1) storage!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment