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; + } + }; 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; + } + };