From 18268b36c1d2205c667ef3019daf1ac561f6e51e Mon Sep 17 00:00:00 2001 From: In Lee Date: Sat, 14 Sep 2024 11:46:06 +0900 Subject: [PATCH 1/2] best-time-to-buy-and-sell-stock solution --- best-time-to-buy-and-sell-stock/seona926.js | 23 +++++++++++++++++++++ 1 file changed, 23 insertions(+) create mode 100644 best-time-to-buy-and-sell-stock/seona926.js diff --git a/best-time-to-buy-and-sell-stock/seona926.js b/best-time-to-buy-and-sell-stock/seona926.js new file mode 100644 index 000000000..532c83f96 --- /dev/null +++ b/best-time-to-buy-and-sell-stock/seona926.js @@ -0,0 +1,23 @@ +function maxProfit(prices) { + let minPrice = Infinity; // 최소 가격을 무한대로 초기화 + let maxProfit = 0; // 최대 이익은 0으로 시작 + + for (let i = 0; i < prices.length; i++) { + if (prices[i] < minPrice) { + // 더 작은 가격을 발견하면 그 가격을 최소 가격으로 업데이트 + minPrice = prices[i]; + } else { + // 현재 가격에서 최소 가격을 뺀 값을 계산하여 최대 이익을 업데이트 + maxProfit = Math.max(maxProfit, prices[i] - minPrice); + } + } + + return maxProfit; +} + +/* + 1. 시간복잡도: O(n) + - 배열을 한 번 순회 + 2. 공간복잡도: O(1) + - 상수 공간 사용 +*/ \ No newline at end of file From c973a58e9efebe978471e9b1dcfa64c9158bde43 Mon Sep 17 00:00:00 2001 From: In Lee Date: Sat, 14 Sep 2024 11:51:10 +0900 Subject: [PATCH 2/2] =?UTF-8?q?=EC=A4=84=EB=B0=94=EA=BF=88=20=EC=B6=94?= =?UTF-8?q?=EA=B0=80?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- best-time-to-buy-and-sell-stock/seona926.js | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/best-time-to-buy-and-sell-stock/seona926.js b/best-time-to-buy-and-sell-stock/seona926.js index 532c83f96..5f1bac76c 100644 --- a/best-time-to-buy-and-sell-stock/seona926.js +++ b/best-time-to-buy-and-sell-stock/seona926.js @@ -20,4 +20,4 @@ function maxProfit(prices) { - 배열을 한 번 순회 2. 공간복잡도: O(1) - 상수 공간 사용 -*/ \ No newline at end of file +*/