JSFiddle - React, Tailwind, and code Playground
by thewolff
JavaScript
function maxStockProfit(pricesArr) {
let maxProfit = -1;
let buyPrice = 0;
let sellPrice = 0;
let changeBuyPrice = true;
for(let i = 0, len = pricesArr.length; i < len; i++) {
if(changeBuyPrice) {
buyPrice = pricesArr[i]
}
sellPrice = pricesArr[i+1]
if(sellPrice < buyPrice) {
changeBuyPrice = true;
} else {
let tempProfit = sellPrice - buyPrice;
if(tempProfit > maxProfit) {
maxProfit = tempProfit
}
changeBuyPrice = false;
}
}
console.log(maxProfit)
return maxProfit;
}
maxStockProfit([36,46,26,38,40,48,42])