Skip to content

Commit 8110030

Browse files
authored
Merge pull request #1400 from Moonjonghoo/main
[moonjonghoo] Week 05 Solutions
2 parents e0ca496 + fd8d099 commit 8110030

File tree

3 files changed

+77
-0
lines changed

3 files changed

+77
-0
lines changed
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,24 @@
1+
/**
2+
* @param {number[]} prices
3+
* @return {number}
4+
*/
5+
var maxProfit = function (prices) {
6+
let minPrices = Infinity;
7+
let profit = 0;
8+
for (price of prices) {
9+
minPrices = Math.min(price, minPrices);
10+
profit = Math.max(profit, price - minPrices);
11+
}
12+
return profit;
13+
};
14+
15+
var maxProfit = function (prices) {
16+
let maxProfit = 0;
17+
let currentProfit = 0;
18+
for (let i = 1; i < prices.length; i++) {
19+
let diff = prices[i] - prices[i - 1];
20+
currentProfit = Math.max(0, currentProfit + diff);
21+
maxProfit = Math.max(maxProfit, currentProfit);
22+
}
23+
return maxProfit;
24+
};

group-anagrams/moonjonghoo.js

+22
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,22 @@
1+
/**
2+
* @param {string[]} strs
3+
* @return {string[][]}
4+
*/
5+
var groupAnagrams = function (strs) {
6+
let hashMap = new Map();
7+
for (let i = 0; i < strs.length; i++) {
8+
let key = strs[i].split("").sort().join("");
9+
if (!hashMap.has(key)) {
10+
hashMap.set(key, [strs[i]]);
11+
} else {
12+
hashMap.set(key, [...hashMap.get(key), strs[i]]);
13+
}
14+
}
15+
let answer = [];
16+
for ([key, value] of hashMap) {
17+
answer.push(value);
18+
}
19+
return answer.sort((a, b) => a.length - b.length).map((arr) => arr.sort());
20+
};
21+
22+
console.log(groupAnagrams(["eat", "tea", "tan", "ate", "nat", "bat"]));

word-break/moonjonghoo.js

+31
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,31 @@
1+
/**
2+
* @param {string} s
3+
* @param {string[]} wordDict
4+
* @return {boolean}
5+
*/
6+
var wordBreak = function (s, wordDict) {
7+
const memo = new Map(); // 실패/성공 여부 기억
8+
const wordSet = new Set(wordDict); // lookup 최적화
9+
10+
function canBreak(sub) {
11+
if (sub === "") return true;
12+
13+
if (memo.has(sub)) return memo.get(sub);
14+
15+
for (let i = 1; i <= sub.length; i++) {
16+
const prefix = sub.slice(0, i);
17+
if (wordSet.has(prefix)) {
18+
const suffix = sub.slice(i);
19+
if (canBreak(suffix)) {
20+
memo.set(sub, true);
21+
return true;
22+
}
23+
}
24+
}
25+
26+
memo.set(sub, false); // 실패한 경우도 기억
27+
return false;
28+
}
29+
30+
return canBreak(s);
31+
};

0 commit comments

Comments
 (0)