Skip to content

[sungjinwi] Week 05 Solution #1413

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 2 commits into from
May 8, 2025
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
37 changes: 37 additions & 0 deletions best-time-to-buy-and-sell-stock/sungjinwi.cpp
Original file line number Diff line number Diff line change
@@ -0,0 +1,37 @@
/*
풀이 :
현재의 price에 도달하기 전 가장 작은 price를 min_cur로 업데이트
price - min_cur가 저장되있는 max_profit보다 크면 값을 업데이트

prices의 개수 N

TC : O(N)

SC : O(1)
*/


#include <vector>
using namespace std;

class Solution {
public:
int maxProfit(vector<int>& 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;
}
};
44 changes: 44 additions & 0 deletions group-anagrams/sungjinwi.cpp
Original file line number Diff line number Diff line change
@@ -0,0 +1,44 @@
/*
풀이 :
strs의 각 str에 대해 정렬을 통해 아나그램을 동일한 판별할 수 있도록 하고
해시테이블 unordered_map에 ans 중 어느 인덱스에 속하는 아나그램인지 판별하도록 한다

이전에 저장되지 않은 아나그램일 경우 새로운 vector<string>을 ans에 추가하고
unordered_map에 추가해준다

strs의 개수 N, 평균 길이 L

TC : O(N * L log(L))
strs의 개수(N)만큼 반복문을 실시하고 sort는 L log(L)의 시간복잡도를 가져서

SC : O(N * L)
해시테이블 lookup의 크기는 최대 개수 * 평균길이 만큼 할당될 수 있으므로 (다 안겹칠 경우우)
*/

#include <vector>
#include <string>
using namespace std;

class Solution {
public:
vector<vector<string>> groupAnagrams(vector<string>& strs) {
int index = 0;
unordered_map<string, int> lookup;
vector<vector<string>> 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<string>{str});
}
}
return ans;
}
};