From 8865bf27277b4ca7d7be50adad04a5fd1061266b Mon Sep 17 00:00:00 2001 From: BangDori Date: Mon, 16 Dec 2024 19:32:57 +0900 Subject: [PATCH] Best Time to Buy and Sell Stock --- bangdori/Best Time to Buy and Sell Stock.js | 18 ++++++++++++++++++ 1 file changed, 18 insertions(+) create mode 100644 bangdori/Best Time to Buy and Sell Stock.js diff --git a/bangdori/Best Time to Buy and Sell Stock.js b/bangdori/Best Time to Buy and Sell Stock.js new file mode 100644 index 0000000..4332328 --- /dev/null +++ b/bangdori/Best Time to Buy and Sell Stock.js @@ -0,0 +1,18 @@ +/** + * @param {number[]} prices + * @return {number} + */ +var maxProfit = function (prices) { + let buyPrice = Infinity; + let maxProfit = 0; + + for (const price of prices) { + if (buyPrice > price) { + buyPrice = price; + } else { + maxProfit = Math.max(maxProfit, price - buyPrice); + } + } + + return maxProfit; +};