Skip to content

Commit 5550dc5

Browse files
committed
Container with Most Water
1 parent 36dcc95 commit 5550dc5

File tree

1 file changed

+28
-0
lines changed

1 file changed

+28
-0
lines changed
Lines changed: 28 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,28 @@
1+
/**
2+
* Time Complexity: O(n), hit each element in the array once
3+
* Space Complexity:O(1), constant space regardless of input size
4+
*/
5+
public class ContainerWithMostWater {
6+
7+
public int maxArea(int[] height) {
8+
if (height == null || height.length < 2) {
9+
return 0;
10+
}
11+
12+
int left = 0;
13+
int right = height.length - 1;
14+
int maxArea = 0;
15+
16+
while (left < right) {
17+
int minHeight = Math.min(height[left], height[right]);
18+
int currentArea = minHeight * (right - left);
19+
maxArea = Math.max(currentArea, maxArea);
20+
if (height[left] < height[right]) {
21+
left++;
22+
} else {
23+
right--;
24+
}
25+
}
26+
return maxArea;
27+
}
28+
}

0 commit comments

Comments
 (0)