Skip to content

Commit fa11b37

Browse files
authored
Merge pull request #1385 from byol-han/main
[byol-han] WEEK 05 solutions
2 parents b4122dd + 256c5f2 commit fa11b37

File tree

3 files changed

+68
-0
lines changed

3 files changed

+68
-0
lines changed
Lines changed: 18 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,18 @@
1+
/**
2+
* @param {number[]} prices
3+
* @return {number}
4+
*/
5+
var maxProfit = function (prices) {
6+
let minPrice = Infinity;
7+
let maxProfit = 0;
8+
9+
for (let i = 0; i < prices.length; i++) {
10+
if (prices[i] < minPrice) {
11+
minPrice = prices[i]; // 지금까지 가장 싼 날
12+
} else if (prices[i] - minPrice > maxProfit) {
13+
maxProfit = prices[i] - minPrice; // 현재 이익이 최대 이익보다 클 때 maxProfit 갱신
14+
}
15+
}
16+
17+
return maxProfit;
18+
};

group-anagrams/byol-han.js

Lines changed: 21 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,21 @@
1+
/**
2+
* @param {string[]} strs
3+
* @return {string[][]}
4+
*/
5+
var groupAnagrams = function (strs) {
6+
const map = new Map();
7+
8+
for (let str of strs) {
9+
// 문자열을 정렬해서 key로 사용
10+
const key = str.split("").sort().join("");
11+
12+
// key가 이미 있다면 배열에 추가, 없으면 새로 생성
13+
if (!map.has(key)) {
14+
map.set(key, []);
15+
}
16+
map.get(key).push(str);
17+
}
18+
19+
// 값만 모아서 배열로 반환
20+
return Array.from(map.values());
21+
};

word-break/byol-han.js

Lines changed: 29 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,29 @@
1+
/**
2+
* https://leetcode.com/problems/word-break/
3+
* @param {string} s
4+
* @param {string[]} wordDict
5+
* @return {boolean}
6+
*/
7+
var wordBreak = function (s, wordDict) {
8+
const wordSet = new Set(wordDict);
9+
const dp = new Array(s.length + 1).fill(false);
10+
dp[0] = true; // 빈 문자열은 항상 true
11+
12+
for (let i = 1; i <= s.length; i++) {
13+
for (let j = 0; j < i; j++) {
14+
if (dp[j] && wordSet.has(s.substring(j, i))) {
15+
dp[i] = true;
16+
break;
17+
}
18+
}
19+
}
20+
21+
return dp[s.length];
22+
};
23+
24+
/*
25+
Set은 검색이 빠르다
26+
wordDict가 배열이면, includes()로 단어가 있는지 찾을 때 O(n) 시간이 걸림
27+
하지만 Set을 사용하면 has() 메서드로 단어가 있는지 O(1) 시간이 걸림
28+
이 차이는 s.length가 길거나 wordDict가 클수록 성능에 큰 영향
29+
*/

0 commit comments

Comments
 (0)