File tree Expand file tree Collapse file tree 2 files changed +52
-15
lines changed
best-time-to-buy-and-sell-stock Expand file tree Collapse file tree 2 files changed +52
-15
lines changed Original file line number Diff line number Diff line change 1+ /**
2+ * 한글주석만 보고 코드를 작성해본다.
3+ * 조건문 안의 조건만 코드를 비우거나, 조건문만 남기고 안의 액션코드를 비우고 다시 작성해본다.
4+ *
5+ */
16class Solution {
27 public int maxProfit (int [] prices ) {
38 /**
49 max라는 메모이제이션 변수를 int로 선언한다.
510 dp로 모든 경우의 수를 고려할 것이다.
6-
711 주식의 최소가격을 담은 변수를 int로 선언한다. 맨 처음에 prices[0] 값이 되면 좋겠다.
8-
9-
1012 */
11- int max = 0 ;
12- int minStock = prices [0 ];
13-
13+ int max = 0 ; // dp memoization 변수
14+ int min = prices [0 ]; // 주식 배열의 최소값
1415 for (int i = 1 ; i < prices .length ; i ++) {
1516 /**
1617 현재 주식은 팔 때의 주식 가격을 나타낸다.
17- max에는 현재 주식 가격 - 현재 최소 주식 가격의 값을 저장한다. (abs 금지)
18- 만약 현재 주식의 가격이 현재 최소 주식 가격보다 크다면
19- 현재 최소 주식의 가격으로 업데이트한다.
18+ max값은 (기존 최대이익, 최소주식을 현재 주식값에 팔았을 때의 이익) 중 더 큰 값으로 업데이트된다.
19+ 현재 주식값이 기존 최소 주식값보다 작다면 현재 주식값으로 최솟값을 업데이트한다.
2020 */
21- int prc = prices [i ];
22- max = Math .max (max , prc - minStock );
23-
24- if (minStock > prc ) {
25- minStock = prc ;
21+ int currentMax = prices [i ] - min ;
22+ max = Math .max (max , currentMax );
23+ if (prices [i ] < min ) {
24+ min = prices [i ];
2625 }
2726 }
27+
2828 return max ;
2929 }
30- }
30+ }
Original file line number Diff line number Diff line change 1+ import java .util .*;
2+ import java .util .stream .Collectors ;
3+
4+ class Solution {
5+ /**
6+ * 41ms를 가진 낮은 성능의 첫번째 정답 코드
7+ */
8+ public List <List <String >> groupAnagrams (String [] strs ) {
9+ // 길이가 1이면 자체를 List로 감싸서 반환한다.
10+ if (strs .length == 1 ) {
11+ return List .of (List .of (strs [0 ]));
12+ }
13+
14+ List <List <String >> groupList = new ArrayList <>();
15+ /**
16+ * bf로 그룹핑을 할 수 있나?
17+ * strs를 for문으로 돌면서 "정렬한" 단어가 map에 있는 지 확인하고 존재할 경우 key로 조회한 list에 추가한다.
18+ * 마지막으로 map을 순회하면서 list들을 groupList.add(list); 한다.
19+ */
20+ Map <String , List <String >> map = new HashMap <>();
21+ for (String s : strs ) {
22+ String sortedS = Arrays .stream (s .split ("" ))
23+ .sorted ()
24+ .collect (Collectors .joining ());
25+ List <String > v = map .get (sortedS );
26+ if (v == null ) {
27+ map .put (sortedS , new ArrayList <>());
28+ }
29+ map .get (sortedS ).add (s );
30+ }
31+
32+ for (List <String > list : map .values ()) {
33+ groupList .add (list );
34+ }
35+ return groupList ;
36+ }
37+ }
You can’t perform that action at this time.
0 commit comments