File tree Expand file tree Collapse file tree 2 files changed +35
-10
lines changed
main/java/com/fishercoder/solutions
test/java/com/fishercoder Expand file tree Collapse file tree 2 files changed +35
-10
lines changed Original file line number Diff line number Diff line change 2
2
3
3
public class _11 {
4
4
public static class Solution1 {
5
+ /**
6
+ * Time: O(n^2)
7
+ * This brute force solution is NOT accepted on LeetCode due to TLE.
8
+ */
9
+ public int maxArea (int [] height ) {
10
+ int maxArea = 0 ;
11
+ for (int left = 0 ; left < height .length - 1 ; left ++) {
12
+ for (int right = height .length - 1 ; left < right ; right --) {
13
+ int area = (right - left ) * Math .min (height [left ], height [right ]);
14
+ maxArea = Math .max (maxArea , area );
15
+ }
16
+ }
17
+ return maxArea ;
18
+ }
19
+ }
20
+
21
+ public static class Solution2 {
22
+ /**
23
+ * Two pointer technique.
24
+ * Well explained here: https://leetcode.com/problems/container-with-most-water/discuss/6100/Simple-and-clear-proofexplanation
25
+ */
5
26
public int maxArea (int [] height ) {
6
27
int max = 0 ;
7
- int i = 0 ;
8
- int j = height .length - 1 ;
9
- while (i < j ) {
10
- max = Math .max (Math .min (height [i ], height [j ]) * (j - i ), max );
11
- if (height [i ] <= height [j ]) {
12
- // we need to find the shorter one,
13
- // then calculate its area
14
- i ++;
28
+ int left = 0 ;
29
+ int right = height .length - 1 ;
30
+ while (left < right ) {
31
+ max = Math .max (Math .min (height [left ], height [right ]) * (right - left ), max );
32
+ if (height [left ] <= height [right ]) {
33
+ /**if this height is shorter, then we'll need to move it to the right to find a higher one so that it's possible to find a larger area.*/
34
+ left ++;
15
35
} else {
16
- j --;
36
+ right --;
17
37
}
18
38
}
19
39
return max ;
Original file line number Diff line number Diff line change 8
8
9
9
public class _11Test {
10
10
private static _11 .Solution1 solution1 ;
11
+ private static _11 .Solution2 solution2 ;
11
12
private static int [] height ;
13
+ private static int expected ;
12
14
13
15
@ BeforeClass
14
16
public static void setup () {
15
17
solution1 = new _11 .Solution1 ();
18
+ solution2 = new _11 .Solution2 ();
16
19
}
17
20
18
21
@ Test
19
22
public void test1 () {
20
23
height = new int []{1 , 1 };
21
- assertEquals (1 , solution1 .maxArea (height ));
24
+ expected = 1 ;
25
+ assertEquals (expected , solution1 .maxArea (height ));
26
+ assertEquals (expected , solution2 .maxArea (height ));
22
27
}
23
28
24
29
}
You can’t perform that action at this time.
0 commit comments