From 8fd950f2b9acedd4dabd748d82fad2d0e142f07a Mon Sep 17 00:00:00 2001 From: yuhyeon99 Date: Mon, 8 Dec 2025 17:09:28 +0900 Subject: [PATCH] best-time-to-buy-and-sell-stock solution --- best-time-to-buy-and-sell-stock/yuhyeon99.js | 19 +++++++++++++++++++ 1 file changed, 19 insertions(+) create mode 100644 best-time-to-buy-and-sell-stock/yuhyeon99.js diff --git a/best-time-to-buy-and-sell-stock/yuhyeon99.js b/best-time-to-buy-and-sell-stock/yuhyeon99.js new file mode 100644 index 0000000000..4e749950e2 --- /dev/null +++ b/best-time-to-buy-and-sell-stock/yuhyeon99.js @@ -0,0 +1,19 @@ +/** + * @param {number[]} prices + * @return {number} + * i 번째 날에 주식의 가격을 prices[i]에 담고 있는 배열 prices가 주어졌을 때, + * 주식을 어떤 날에 한 번 사고 나중에 다른 날에 팔아서 달성 가능한 최대 이익을 구하라. + * + */ +var maxProfit = function(prices) { + var maxProfit = 0; + var minPrice = prices[0] + + for(let i = 0; i < prices.length; i ++) { + let profit = prices[i] - minPrice; + maxProfit = Math.max(profit, maxProfit); + minPrice = Math.min(prices[i], minPrice); + } + + return maxProfit; +};