From 9d2f7ad754b2226469d64e87834ea03bdcf0cc78 Mon Sep 17 00:00:00 2001 From: Jinyoung Jeong <80400463+jyoung2419@users.noreply.github.com> Date: Fri, 23 Oct 2026 22:48:25 +0900 Subject: [PATCH] Create 121. Best Time to Buy and Sell Stock --- .../121. Best Time to Buy and Sell Stock" | 27 +++++++++++++++++++ 1 file changed, 27 insertions(+) create mode 100644 "leetcode3/\354\240\225\354\247\204\354\230\201/121. Best Time to Buy and Sell Stock" diff --git "a/leetcode3/\354\240\225\354\247\204\354\230\201/121. Best Time to Buy and Sell Stock" "b/leetcode3/\354\240\225\354\247\204\354\230\201/121. Best Time to Buy and Sell Stock" new file mode 100644 index 00000000..5c19d01b --- /dev/null +++ "b/leetcode3/\354\240\225\354\247\204\354\230\201/121. Best Time to Buy and Sell Stock" @@ -0,0 +1,27 @@ +/** + * @param {number[]} prices + * @return {number} + */ +var maxProfit = function(prices) { + /* + 1. 아이디어 + - prices[0]을 최소매수값으로 설정 + - for 문 돌면서 prices[i] - 최소매수값 을 profit 최대값으로 갱신 + - prices[i] 이랑 비교해가며 최소매수값 갱신 + 2. 시간복잡도 + - O(n) + 3. 자료구조 + - 최소값 : minPrice + - 이익 : profit + */ + + let profit = 0; + let minPrice = prices[0]; + + for (let i = 1; i < prices.length; i++){ + profit = Math.max(profit, prices[i] - minPrice); + minPrice = Math.min(minPrice, prices[i]); + } + + return profit; +};