Skip to content

Instantly share code, notes, and snippets.

@primaryobjects
Last active March 14, 2025 02:28
Show Gist options
  • Save primaryobjects/a3375af43251e7ea7824fec0ffb4285c to your computer and use it in GitHub Desktop.
Save primaryobjects/a3375af43251e7ea7824fec0ffb4285c to your computer and use it in GitHub Desktop.
Best Time to Buy and Sell Stock https://jsfiddle.net/tg17v03c/
const maxProfit = prices => {
let left = 0;
let right = 1;
let maxProfit = 0;
while (right < prices.length) {
if (prices[left] < prices[right]) {
const profit = prices[right] - prices[left];
maxProfit = Math.max(maxProfit, profit);
}
else {
left = right;
}
right++;
}
return maxProfit;
}
console.log(maxProfit([10,1,5,6,7,1]));
console.log(maxProfit([10,8,7,5,2]));
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment