Skip to content
Open
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
42 changes: 42 additions & 0 deletions best-time-to-buy-and-sell-stock/Cyjin-jani.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,42 @@
// naive하게 풀면, time limit 초과함
// O(n^2) 풀이가 되기 때문..
const maxProfit_naive = function (prices) {
let profit = 0;

for (let i = 0; i < prices.length - 1; i++) {
const buy = prices[i];
for (let j = i + 1; j < prices.length; j++) {
const newProfit = prices[j] - buy;
if (newProfit > profit) {
profit = newProfit;
}
}
}

return profit;
};

// 투포인터 사용하여 풀기
// tc: O(n)
// sc: O(1)
const maxProfit = function (prices) {
let buyIdx = 0;
let sellIdx = 1;

while (sellIdx < prices.length) {
let buyPrice = prices[buyIdx];
let sellPrice = prices[sellIdx];

// 더 낮은 가격에 매수 가능한 날을 찾으면 바로 거기서부터 재탐색
if (buyPrice > sellPrice) {
buyIdx = sellIdx;
} else {
let newProfit = sellPrice - buyPrice;
profit = Math.max(profit, newProfit);
}

sellIdx++;
}

return profit;
};
95 changes: 95 additions & 0 deletions group-anagrams/Cyjin-jani.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,95 @@
const isAnagram = function (s, t) {
if (s.length !== t.length) return false;

const data = new Map();

for (let char of s) {
data.set(char, (data.get(char) || 0) + 1);
}

for (let char of t) {
if (!data.get(char)) return false;
data.set(char, data.get(char) - 1);
}

return true;
};

// Time Limit Exceeded로 fail..
// tc: O(n^2);
// sc: O(n)
const groupAnagrams_naive = function (strs) {
if (strs.length < 2) return [strs];

const answer = [];

while (strs.length > 0) {
let temp = [strs[0]];

if (strs.length < 2) return answer;

strs.splice(0, 1);

for (let j = 0; j < strs.length; j++) {
if (isAnagram(temp[0], strs[j])) {
// 같다면, temp 배열에 넣음
temp.push(strs[j]);
}
}
answer.push(temp);

temp.forEach((t) => {
const idx = strs.indexOf(t);
if (idx !== -1) {
strs.splice(idx, 1);
}
});

if (strs.length === 1) {
answer.push(strs);
}
}

return answer;
};

// splice 같은 로직이 없어서 겨우 TLE을 통과했지만 여전히 O(n²)인 점은 변함이 없음.
const groupAnagrams_set = function (strs) {
const visited = new Set();
const answer = [];

for (let i = 0; i < strs.length; i++) {
if (visited.has(i)) continue;

const group = [strs[i]];

for (let j = i + 1; j < strs.length; j++) {
if (!visited.has(j) && isAnagram(strs[i], strs[j])) {
group.push(strs[j]);
visited.add(j);
}
}

answer.push(group);
}

return answer;
};

//! AI로부터 힌트를 얻어 풀어봤습니다..
// tc: O(nlogn)
// sc: O(n)
const groupAnagrams = function (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 [...map.values()];
};
Loading