Last active
February 8, 2021 12:48
-
-
Save nickGermi/76f2f13c6d762bb7d6094c9a479b4e3c 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
var stockPrices = [10, 7, 5, 8, 11, 9]; | |
/* | |
Takes an array of stock prices and returns the best profit could have been made from 1 purchase and 1 sale of 1 stock | |
*/ | |
function getProfit(inputArray){ | |
//find minimum of first 2 items of the array | |
var min = inputArray[0] < inputArray[1] ? inputArray[0] : inputArray[1]; | |
//find difference of second item minus first | |
var diff = inputArray[1] - inputArray[0]; | |
//optional container for buy, sell and profit margin | |
var trade = {buy: 0, sell: 0, profit: diff}; | |
//iterate over each item of array, forEach is faster and safer than for loop | |
inputArray.forEach(function(price, index){ | |
//skip first 2 since we have already compared them | |
if(index>1){ | |
//if current price is less than minimum then current price is the new minimum | |
if (price < min) min = price; | |
//if current price minus minimum is bigger than previous difference then new difference is equal current price minus current minimum | |
if (price - min > diff) diff = price - min; | |
//optional, if profit/diff has increased, store the current price as well as the best minimum | |
if (trade.profit < diff) { | |
trade.buy = min; | |
trade.sell = price; | |
trade.profit = diff; | |
} | |
} | |
}); | |
//optional, print buy, sell and profit margins | |
console.log('Buy when $'+trade.buy+' and sell when $'+trade.sell+' for profit of $'+trade.profit); | |
//return the best profit | |
return (diff); | |
} | |
//print output | |
console.log(getProfit(stockPrices)); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment