Last active
September 11, 2016 22:16
-
-
Save jessemillar/babb214bacc498fc22743aeff707c5b3 to your computer and use it in GitHub Desktop.
This file contains 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
// 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)); |
Now accounts for negative values being the best return on investment.
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
Currently has an
O(n^2)
complexity which isn't great...