diff --git a/best-time-to-buy-and-sell-stock/reeseo3o.js b/best-time-to-buy-and-sell-stock/reeseo3o.js new file mode 100644 index 000000000..637a660b8 --- /dev/null +++ b/best-time-to-buy-and-sell-stock/reeseo3o.js @@ -0,0 +1,31 @@ +// Step 1. 브루트 포스 +// 시간 복잡도: O(n²) +const maxProfitBrute = (prices) => { + let maxProfit = 0; + + for (let i = 0; i < prices.length; i++) { + for (let j = i + 1; j < prices.length; j++) { + const profit = prices[j] - prices[i]; + maxProfit = Math.max(maxProfit, profit); + } + } + + return maxProfit; +} + +// Step 2. 최적 풀이 +// 시간 복잡도: O(n) +const maxProfit = (prices) => { + let minPrice = Infinity; + let maxProfit = 0; + + for (const price of prices) { + if (price < minPrice) { + minPrice = price; + } else { + maxProfit = Math.max(maxProfit, price - minPrice); + } + } + + return maxProfit; +} diff --git a/group-anagrams/reeseo3o.js b/group-anagrams/reeseo3o.js new file mode 100644 index 000000000..f66648033 --- /dev/null +++ b/group-anagrams/reeseo3o.js @@ -0,0 +1,19 @@ +/** + * TC: O(n * k log k) — 각 단어(k) 정렬 × n개 + * SC: O(n * k) + */ +const groupAnagrams = (strs) => { + const map = new Map(); + + for (const str of strs) { + const key = str.split("").sort().join(""); + + if (!map.has(key)) { + map.set(key, []); + } + + map.get(key).push(str); + } + + return Array.from(map.values()); +};