File tree Expand file tree Collapse file tree 1 file changed +63
-0
lines changed
container-with-most-water Expand file tree Collapse file tree 1 file changed +63
-0
lines changed Original file line number Diff line number Diff line change
1
+ // tc: O(n)
2
+ // 투 포인터라는 문제풀이 방법으로 간단히 (답지보고) 해결...
3
+ class Solution {
4
+ public int maxArea (int [] h ) {
5
+ int start = 0 ;
6
+ int end = h .length - 1 ;
7
+ int mx = -987654321 ;
8
+
9
+ while (start < end ) {
10
+ mx = Math .max (mx , (end - start ) * Math .min (h [start ], h [end ]));
11
+
12
+ if (h [start ] < h [end ]) {
13
+ start ++;
14
+ } else {
15
+ end --;
16
+ }
17
+ }
18
+
19
+ return mx ;
20
+ }
21
+ }
22
+
23
+
24
+ // 예외처리가 덕지덕지 붙기 시작할 때. (잘못됨을 깨닫고)다른 방법으로 풀어햐 하는건 아닌지 생각하는 습관 필요함..ㅠ
25
+ class WrongSolution {
26
+ public int maxArea (int [] h ) {
27
+ int mx = Math .min (h [0 ], h [1 ]);
28
+ int idx = 0 ;
29
+
30
+ for (int i = 1 ; i < h .length ; i ++) {
31
+ int offset = i - idx ;
32
+
33
+ int prevCalc = Math .min (h [i - 1 ], h [i ]);
34
+ int calc = Math .min (h [idx ], h [i ]);
35
+ int newMx = calc * offset ;
36
+
37
+ // 새롭게 인덱스를 바꿔버리는게 더 나을때.
38
+ if (prevCalc > newMx ) {
39
+ idx = i - 1 ;
40
+ mx = Math .max (mx , prevCalc );
41
+ continue ;
42
+ }
43
+
44
+ // 물을 더 많이 담을 수 있을 때.
45
+ if (h [idx ] < h [i ] && newMx > mx ) {
46
+ if (i == 2 ) {
47
+ int exc = Math .min (h [1 ], h [i ]) * offset ;
48
+ if (exc > newMx ) {
49
+ idx = 1 ;
50
+ mx = Math .max (exc , mx );
51
+ continue ;
52
+ }
53
+ }
54
+
55
+ idx = i ;
56
+ }
57
+
58
+ mx = Math .max (newMx , mx );
59
+ }
60
+
61
+ return mx ;
62
+ }
63
+ }
You can’t perform that action at this time.
0 commit comments