From 9c8ca7e8e93390171ba2e448e50cc0f1461d8bf0 Mon Sep 17 00:00:00 2001 From: sungjinwi <0202wsj@gmail.com> Date: Sat, 3 May 2025 20:15:18 +0900 Subject: [PATCH 1/2] #221 solution --- best-time-to-buy-and-sell-stock/sungjinwi.cpp | 37 +++++++++++++++++++ 1 file changed, 37 insertions(+) create mode 100644 best-time-to-buy-and-sell-stock/sungjinwi.cpp diff --git a/best-time-to-buy-and-sell-stock/sungjinwi.cpp b/best-time-to-buy-and-sell-stock/sungjinwi.cpp new file mode 100644 index 000000000..853da95b5 --- /dev/null +++ b/best-time-to-buy-and-sell-stock/sungjinwi.cpp @@ -0,0 +1,37 @@ +/* + 풀이 : + 현재의 price에 도달하기 전 가장 작은 price를 min_cur로 업데이트 + price - min_cur가 저장되있는 max_profit보다 크면 값을 업데이트 + + prices의 개수 N + + TC : O(N) + + SC : O(1) +*/ + + +#include +using namespace std; + +class Solution { + public: + int maxProfit(vector& prices) { + int min_cur = prices[0]; + int max_profit = 0; + + for (int& price : prices) + { + if (price < min_cur) + { + min_cur = price; + continue ; + } + + int profit = price - min_cur; + if (profit > max_profit) + max_profit = profit; + } + return max_profit; + } + }; From 957ce04ee3cd4b5162b5781c5156ab5b23374e98 Mon Sep 17 00:00:00 2001 From: sungjinwi <0202wsj@gmail.com> Date: Sat, 3 May 2025 22:23:39 +0900 Subject: [PATCH 2/2] #236 group-anagrams solution --- group-anagrams/sungjinwi.cpp | 44 ++++++++++++++++++++++++++++++++++++ 1 file changed, 44 insertions(+) create mode 100644 group-anagrams/sungjinwi.cpp diff --git a/group-anagrams/sungjinwi.cpp b/group-anagrams/sungjinwi.cpp new file mode 100644 index 000000000..84b678118 --- /dev/null +++ b/group-anagrams/sungjinwi.cpp @@ -0,0 +1,44 @@ +/* + 풀이 : + strs의 각 str에 대해 정렬을 통해 아나그램을 동일한 판별할 수 있도록 하고 + 해시테이블 unordered_map에 ans 중 어느 인덱스에 속하는 아나그램인지 판별하도록 한다 + + 이전에 저장되지 않은 아나그램일 경우 새로운 vector을 ans에 추가하고 + unordered_map에 추가해준다 + + strs의 개수 N, 평균 길이 L + + TC : O(N * L log(L)) + strs의 개수(N)만큼 반복문을 실시하고 sort는 L log(L)의 시간복잡도를 가져서 + + SC : O(N * L) + 해시테이블 lookup의 크기는 최대 개수 * 평균길이 만큼 할당될 수 있으므로 (다 안겹칠 경우우) +*/ + +#include +#include +using namespace std; + +class Solution { + public: + vector> groupAnagrams(vector& strs) { + int index = 0; + unordered_map lookup; + vector> ans; + + for (string& str : strs) + { + string sorted = str; + sort(sorted.begin(), sorted.end()); + if(lookup.count(sorted)) + ans[lookup[sorted]].push_back(str); + else + { + lookup[sorted] = index; + index++; + ans.push_back(vector{str}); + } + } + return ans; + } + };