Skip to content

Commit 27301f5

Browse files
authored
Merge pull request #2157 from hjeomdev/main
[hjeomdev] WEEK 05 solutions
2 parents 51087ff + 1dfd2bf commit 27301f5

File tree

2 files changed

+79
-0
lines changed

2 files changed

+79
-0
lines changed
Lines changed: 58 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,58 @@
1+
class Solution {
2+
public int maxProfit(int[] prices) {
3+
// 1. 0번을 제외하고 max 를 찾고
4+
// 2. 0 ~ max 범위에서 min을 찾는다 => 2n
5+
// 3. max - min > 0 이면 값 리턴, max - min <=0 이면 0 리턴
6+
/*
7+
if (prices.length == 1) {
8+
return 0;
9+
}
10+
11+
int max = 1;
12+
for (int i = 1; i < prices.length; i++) {
13+
if (prices[max] <= prices[i]) {
14+
max = i;
15+
}
16+
}
17+
18+
int min = max - 1;
19+
for (int i = max - 1; i >= 0; i--) {
20+
if (prices[i] < prices[min]) {
21+
min = i;
22+
}
23+
}
24+
int result = prices[max] - prices[min];
25+
return result > 0 ? result : 0;
26+
*/
27+
// 위 풀이 실패 케이스 : [3,3,5,0,0,3,1,4]
28+
// -> i가 max 일 때 i 이전까지 반복문으로 최대값 구하기 => n^2
29+
// -> Time Limit Exceeded 발생
30+
// -> i 이전까지 범위에서 최소값을 구해서 값을 구할까?
31+
/*
32+
int result = 0;
33+
for (int i = 1; i < prices.length; i++) {
34+
for (int j = 0; j < i; j++) {
35+
int cur = prices[i] - prices[j];
36+
if (result < cur) {
37+
result = cur;
38+
}
39+
}
40+
}
41+
return result;
42+
*/
43+
// i 이전까지 범위에서 최소값을 구해서 배열로 만들기
44+
int curMin = prices[0];
45+
int result = 0;
46+
for (int i = 0; i < prices.length; i++) {
47+
if (curMin > prices[i]) {
48+
curMin = prices[i];
49+
}
50+
// System.out.println(curMin);
51+
if (result < prices[i] - curMin) {
52+
result = prices[i] - curMin;
53+
}
54+
// System.out.println(">>" + result);
55+
}
56+
return result;
57+
}
58+
}

group-anagrams/hjeomdev.java

Lines changed: 21 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,21 @@
1+
class Solution {
2+
public List<List<String>> groupAnagrams(String[] strs) {
3+
// 감이 안 와서 해설참조
4+
// 26자리 배열을 사용해서 알파벳 카운트 -> 문자열로 만들어서 Map의 키로 사용
5+
Map<String, List<String>> anagrams = new HashMap<>();
6+
for (String str : strs) {
7+
int[] count = new int[26];
8+
for (char ch : str.toCharArray()) {
9+
int idx = ch - 'a';
10+
count[idx] = count[idx] + 1;
11+
}
12+
String key = Arrays.toString(count);
13+
if (!anagrams.containsKey(key)) {
14+
anagrams.put(key, new LinkedList<>());
15+
}
16+
List<String> words = anagrams.get(key);
17+
words.add(str);
18+
}
19+
return new ArrayList(anagrams.values());
20+
}
21+
}

0 commit comments

Comments
 (0)