Skip to content

[byol-han] WEEK 05 solutions #1385

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 3 commits into from
May 3, 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
18 changes: 18 additions & 0 deletions best-time-to-buy-and-sell-stock/byol-han.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,18 @@
/**
* @param {number[]} prices
* @return {number}
*/
var maxProfit = function (prices) {
let minPrice = Infinity;
let maxProfit = 0;

for (let i = 0; i < prices.length; i++) {
if (prices[i] < minPrice) {
minPrice = prices[i]; // 지금까지 가장 싼 날
} else if (prices[i] - minPrice > maxProfit) {
maxProfit = prices[i] - minPrice; // 현재 이익이 최대 이익보다 클 때 maxProfit 갱신
}
}

return maxProfit;
};
21 changes: 21 additions & 0 deletions group-anagrams/byol-han.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
/**
* @param {string[]} strs
* @return {string[][]}
*/
var groupAnagrams = function (strs) {
const map = new Map();

for (let str of strs) {
// 문자열을 정렬해서 key로 사용
const key = str.split("").sort().join("");

// key가 이미 있다면 배열에 추가, 없으면 새로 생성
if (!map.has(key)) {
map.set(key, []);
}
map.get(key).push(str);
}

// 값만 모아서 배열로 반환
return Array.from(map.values());
};
29 changes: 29 additions & 0 deletions word-break/byol-han.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,29 @@
/**
* https://leetcode.com/problems/word-break/
* @param {string} s
* @param {string[]} wordDict
* @return {boolean}
*/
var wordBreak = function (s, wordDict) {
const wordSet = new Set(wordDict);
const dp = new Array(s.length + 1).fill(false);
dp[0] = true; // 빈 문자열은 항상 true

for (let i = 1; i <= s.length; i++) {
for (let j = 0; j < i; j++) {
if (dp[j] && wordSet.has(s.substring(j, i))) {
dp[i] = true;
break;
}
}
}

return dp[s.length];
};

/*
Set은 검색이 빠르다
wordDict가 배열이면, includes()로 단어가 있는지 찾을 때 O(n) 시간이 걸림
하지만 Set을 사용하면 has() 메서드로 단어가 있는지 O(1) 시간이 걸림
이 차이는 s.length가 길거나 wordDict가 클수록 성능에 큰 영향
*/