Skip to content

Commit 51087ff

Browse files
authored
Merge pull request #2156 from sangyyypark/main
[sangyyypark] WEEK 05 solutions
2 parents de3162c + 44e012c commit 51087ff

File tree

2 files changed

+63
-0
lines changed

2 files changed

+63
-0
lines changed
Lines changed: 22 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,22 @@
1+
/**
2+
3+
์ตœ๋Œ€์ด์ต = ์ตœ๊ณ ๊ธˆ์•ก - ์ตœ์†Œ๊ธˆ์•ก
4+
*/
5+
class Solution {
6+
public int maxProfit(int[] prices) {
7+
int minPrice = Integer.MAX_VALUE;
8+
int maximumProfit = 0;
9+
10+
for(int price : prices) {
11+
if(price < minPrice) {
12+
minPrice = price;
13+
}
14+
int currentProfit = price - minPrice;
15+
if(currentProfit > maximumProfit) {
16+
maximumProfit = currentProfit;
17+
}
18+
}
19+
return maximumProfit;
20+
}
21+
}
22+
Lines changed: 41 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,41 @@
1+
/**
2+
1. ๋ฌธ์ œ์ดํ•ด
3+
anagrams๋Š” ๋‹จ์–ด๊ฐ€ ์žˆ์„๋•Œ ๋‹จ์–ด์— ํฌํ•จ๋œ ์•ŒํŒŒ๋ฒณ ๋นˆ๋„์ˆ˜๊ฐ€ ๋ชจ๋‘ ๋™์ผํ•œ๊ฒƒ์„ ์˜๋ฏธํ•ฉ๋‹ˆ๋‹ค.
4+
group anagrams๋Š” list์— ๋‹จ์–ด๋ชฉ๋ก์ด ์žˆ์„๋•Œ anagrams์ด ๋˜๋Š” ๋‹จ์–ด๋“ค์„ ๋ฐฐ์—ด๋กœ ๊ทธ๋ฃนํ•‘ํ•œ ๋ฆฌ์ŠคํŠธ ์ž…๋‹ˆ๋‹ค.
5+
6+
2. naive algorithm๋„์ถœ
7+
8+
O(N^2) ๋ฐฉ๋ฒ•
9+
2.1.๋‹จ์–ด ํ•˜๋‚˜๋ฅผ ์„ ํƒํ•˜๊ณ , ํ•ด๋‹น ๋‹จ์–ด์˜ ๋นˆ๋„์ˆ˜๋ฅผ ์ €์žฅํ•˜๋Š” Map์„ ์ƒ์„ฑํ•ฉ๋‹ˆ๋‹ค.
10+
2.2ํ•ด๋‹น ๋‹จ์–ด๋ฅผ ์ œ์™ธํ•˜๊ณ  ๋‚˜๋จธ์ง€ ๋‹จ์–ด๋“ค์„ ํƒ์ƒ‰ํ•˜๋ฉด์„œ ๋™์ผํ•œ ๋นˆ๋„์ˆ˜๋ฅผ ๊ฐ€์ง„ ๋‹จ์–ด๋“ค์„ ์ƒˆ๋กœ์šด list์— ์ €์žฅํ•ฉ๋‹ˆ๋‹ค.
11+
12+
๊ฐœ์„ ํฌ์ธํŠธ
13+
๊ฐ ๋‹จ์–ด๋ฅผ ์•ŒํŒŒ๋ฒณ ์˜ค๋ฆ„์ฐจ์ˆœ์œผ๋กœ ์ •๋ ฌ
14+
15+
*/
16+
class sangyyypark {
17+
public List<List<String>> groupAnagrams(String[] strs) {
18+
Map<String,List<String>> map = new HashMap<>();
19+
for(String str : strs) {
20+
String key = sortedString(str);
21+
List<String> group = map.get(key);
22+
if(group != null) {
23+
group.add(str);
24+
}
25+
else {
26+
List<String> newGroup = new ArrayList<>();
27+
newGroup.add(str);
28+
map.put(key, newGroup);
29+
}
30+
}
31+
32+
return new ArrayList<>(map.values());
33+
}
34+
35+
public String sortedString(String str) {
36+
char [] charArr = str.toCharArray();
37+
Arrays.sort(charArr);
38+
return new String(charArr);
39+
}
40+
}
41+

0 commit comments

Comments
ย (0)