From a48ed05be2e12a27505c67a24b07b6e9c34d60a5 Mon Sep 17 00:00:00 2001 From: Hyejin Date: Mon, 28 Apr 2025 23:33:22 +0900 Subject: [PATCH 1/2] Best Time to Buy and Sell Stock solution --- best-time-to-buy-and-sell-stock/clara-shin.js | 33 +++++++++++++++++++ 1 file changed, 33 insertions(+) create mode 100644 best-time-to-buy-and-sell-stock/clara-shin.js diff --git a/best-time-to-buy-and-sell-stock/clara-shin.js b/best-time-to-buy-and-sell-stock/clara-shin.js new file mode 100644 index 000000000..05c0df2a8 --- /dev/null +++ b/best-time-to-buy-and-sell-stock/clara-shin.js @@ -0,0 +1,33 @@ +/** + * 시간 복잡도 O(n) + * 공간 복잡도 O(1) + * + * 그리디 알고리즘 + * 현재까지의 최저 가격을 기억하고, 그 가격에 샀을 때의 이익을 계속 계산하여 최대 이익을 구함 + */ + +/** + * @param {number[]} prices + * @return {number} + */ +var maxProfit = function (prices) { + let minPrice = prices[0]; // 최저 가격 초기화 (첫 날 가격) + let maxProfit = 0; // 최대 이익 초기화 (아직 이익 없음) + + // 두 번째 날부터 + for (let i = 1; i < prices.length; i++) { + // 현재 가격이 최저 가격보다 낮으면 최저 가격 업데이트 + if (prices[i] < minPrice) { + minPrice = prices[i]; + } + // 현재 가능한 이익 계산 (현재 가격 - 최저 가격) + const currentProfit = prices[i] - minPrice; + + // 최대 이익 업데이트 + if (currentProfit > maxProfit) { + maxProfit = currentProfit; + } + } + + return maxProfit; +}; From a01fdcffdb702d216dbcf270e05707ab455ddafe Mon Sep 17 00:00:00 2001 From: Hyejin Date: Tue, 29 Apr 2025 19:01:44 +0900 Subject: [PATCH 2/2] update Best Time to Buy and Sell Stock solution --- best-time-to-buy-and-sell-stock/clara-shin.js | 13 ++----------- 1 file changed, 2 insertions(+), 11 deletions(-) diff --git a/best-time-to-buy-and-sell-stock/clara-shin.js b/best-time-to-buy-and-sell-stock/clara-shin.js index 05c0df2a8..6ca8c13af 100644 --- a/best-time-to-buy-and-sell-stock/clara-shin.js +++ b/best-time-to-buy-and-sell-stock/clara-shin.js @@ -16,17 +16,8 @@ var maxProfit = function (prices) { // 두 번째 날부터 for (let i = 1; i < prices.length; i++) { - // 현재 가격이 최저 가격보다 낮으면 최저 가격 업데이트 - if (prices[i] < minPrice) { - minPrice = prices[i]; - } - // 현재 가능한 이익 계산 (현재 가격 - 최저 가격) - const currentProfit = prices[i] - minPrice; - - // 최대 이익 업데이트 - if (currentProfit > maxProfit) { - maxProfit = currentProfit; - } + minPrice = Math.min(minPrice, prices[i]); // 최저 가격 갱신 + maxProfit = Math.max(maxProfit, prices[i] - minPrice); // 최대 이익 갱신 } return maxProfit;