Skip to content

Commit e3c7c87

Browse files
add a solution for 11
1 parent c850dc9 commit e3c7c87

File tree

2 files changed

+35
-10
lines changed

2 files changed

+35
-10
lines changed

src/main/java/com/fishercoder/solutions/_11.java

Lines changed: 29 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -2,18 +2,38 @@
22

33
public class _11 {
44
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+
*/
526
public int maxArea(int[] height) {
627
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++;
1535
} else {
16-
j--;
36+
right--;
1737
}
1838
}
1939
return max;

src/test/java/com/fishercoder/_11Test.java

Lines changed: 6 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -8,17 +8,22 @@
88

99
public class _11Test {
1010
private static _11.Solution1 solution1;
11+
private static _11.Solution2 solution2;
1112
private static int[] height;
13+
private static int expected;
1214

1315
@BeforeClass
1416
public static void setup() {
1517
solution1 = new _11.Solution1();
18+
solution2 = new _11.Solution2();
1619
}
1720

1821
@Test
1922
public void test1() {
2023
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));
2227
}
2328

2429
}

0 commit comments

Comments
 (0)