Skip to content

Commit a1d5cac

Browse files
Added ContainerWithMostWater.java| Leetcode - 11
1 parent e440136 commit a1d5cac

File tree

1 file changed

+38
-0
lines changed

1 file changed

+38
-0
lines changed
Lines changed: 38 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,38 @@
1+
// Leetcode - 11 - ContainerWithMostWater.java
2+
/**
3+
* Given n non-negative integers a1, a2, ..., an , where each represents a point at coordinate (i, ai). n vertical lines are drawn such that the two endpoints of line i is at (i, ai) and (i, 0). Find two lines, which together with x-axis forms a container, such that the container contains the most water.
4+
5+
Note: You may not slant the container and n is at least 2.
6+
7+
The above vertical lines are represented by array [1,8,6,2,5,4,8,3,7]. In this case, the max area of water (blue section) the container can contain is 49.
8+
9+
Example:
10+
11+
Input: [1,8,6,2,5,4,8,3,7]
12+
Output: 49
13+
*/
14+
public class ContainerWithMostWater {
15+
class Solution {
16+
public int maxArea(int[] height) {
17+
if (height == null || height.length == 0) {
18+
return 0;
19+
}
20+
21+
22+
int i = 0;
23+
int j = height.length - 1;
24+
int area = Integer.MIN_VALUE;
25+
while(i < j) {
26+
int minHeight = Math.min(height[i], height[j]);
27+
area = Math.max(area, minHeight*(j - i));
28+
29+
if(height[i] < height[j]) {
30+
i++;
31+
} else {
32+
j--;
33+
}
34+
}
35+
return area;
36+
}
37+
}
38+
}

0 commit comments

Comments
 (0)