JSFiddle - React, Tailwind, and code Playground
by eitanp461
JavaScript
var stockPricesYesterday = [10, 7, 5, 8, 11, 9];
var stockPricesYesterday1 = [3, 7, 5, 2, 11, 1, 9];
var stockPricesYesterday2 = [5, 4, 3, 2, 1];
console.log(getMaxProfit(stockPricesYesterday2));
// returns 6 (buying for $5 and selling for $11)
function getMaxProfit(stocks) {
const len = stocks.length;
var minPrice = stocks[0];
var maxProfit = stocks[1] - stocks[0];
for (let i = 1; i < len; i++) {
var currentPrice = stocks[i];
// see what our profit would be if we bought at the
// min price and sold at the current price
var potentialProfit = currentPrice - minPrice;
// update maxProfit if we can do better
maxProfit = Math.max(maxProfit, potentialProfit);
// update minPrice so it's always
// the lowest price we've seen so far
minPrice = Math.min(minPrice, currentPrice);
}
return maxProfit;
}