Last active
March 14, 2025 02:28
Best Time to Buy and Sell Stock https://jsfiddle.net/tg17v03c/
This file contains hidden or 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
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