Skip to content

Commit c8cd26c

Browse files
authored
Add files via upload
1 parent 9e08b3a commit c8cd26c

File tree

1 file changed

+35
-0
lines changed

1 file changed

+35
-0
lines changed
Lines changed: 35 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,35 @@
1+
//LeetCode 11. Container with most water
2+
//Question - https://leetcode.com/problems/container-with-most-water/
3+
4+
class Solution {
5+
public int maxArea(int[] height) {
6+
int start = 0;
7+
int end = height.length - 1;
8+
int maxWater = 0;
9+
10+
/*
11+
Brute force solution would be to evaluate all containers. This will take
12+
O(n^2) time. This can be avoided by considering the fact that the
13+
maximum water a container can hold is restricted by the minimum of the
14+
two sides. The minimum value acts as a limiting factor.
15+
16+
There is no point in pairing-up this minimum value with other greater values
17+
as the height is limited by this value.
18+
19+
To gain maximum profit from this value, we need to pair it with the
20+
farthest value which is equal to or greater than this value. This is
21+
the maximum water we can retain with this value and so it is safe to
22+
move the pointer pointing at this minimum value.
23+
*/
24+
25+
while(start < end){
26+
int water = Math.min(height[start], height[end]) * (end - start);
27+
maxWater = Math.max(maxWater, water);
28+
29+
if(height[start] < height[end]) start++;
30+
else end--;
31+
}
32+
33+
return maxWater;
34+
}
35+
}

0 commit comments

Comments
 (0)