Skip to content

Instantly share code, notes, and snippets.

@Ravenstine
Last active June 28, 2022 16:02
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save Ravenstine/87dbf197d6a3a5a686099fdf020eb2c7 to your computer and use it in GitHub Desktop.
Save Ravenstine/87dbf197d6a3a5a686099fdf020eb2c7 to your computer and use it in GitHub Desktop.
best-buy-sell-price.js
function bestBuyAndSellPrices(stockPrices) {
let buyDay = null;
let sellDay = null;
let buyPrice = typeof stockPrices[0] !== 'number' ? null : stockPrices[0];
let sellPrice = buyPrice;
stockPrices.forEach((currentBuyPrice, i) => {
const prevPrice = stockPrices[i - 1];
const nextPrice = stockPrices[i + 1];
const isBuyPrice = ((currentBuyPrice - prevPrice) < 0 && (nextPrice - currentBuyPrice) >= 0);
// only analyze prices if we've bottomed out on a dip
if (!isBuyPrice) return;
let n = i + 1;
// find the best succeeding price to sell at
while (n < stockPrices.length) {
const currentSellPrice = stockPrices[n];
const profit = currentSellPrice - currentBuyPrice;
if (profit > (sellPrice - buyPrice)) {
buyDay = i + 1;
buyPrice = currentBuyPrice;
sellDay = n + 1;
sellPrice = currentSellPrice;
}
n++;
}
});
return {
buyDay,
buyPrice,
sellDay,
sellPrice,
profit: sellPrice - buyPrice,
};
}
console.log(bestBuyAndSellPrices([12, 17, 1, 12, 15, 7, 14, 16, 8, 6]));
console.log(bestBuyAndSellPrices([17, 19, 18, 14, 20, 21, 14, 19, 18, 6]));
console.log(bestBuyAndSellPrices([20, 3, 18, 6, 11, 15, 1, 12, 9, 3, 1, 17, 18, 20, 11]));
console.log(bestBuyAndSellPrices([4]));
console.log(bestBuyAndSellPrices([]));
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment