Skip to content

Commit 9659295

Browse files
Sarvani BaruSarvani Baru
authored andcommitted
Done Two-Pointers-1
1 parent a1c988c commit 9659295

1 file changed

Lines changed: 33 additions & 0 deletions

File tree

‎ContainerWithMostWater.java‎

Lines changed: 33 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,33 @@
1+
// Time Complexity : O(n)
2+
// Space Complexity : O(1)
3+
// Did this code successfully run on Leetcode : yes
4+
// Any problem you faced while coding this : no
5+
6+
// Your code here along with comments explaining your approach
7+
/*
8+
Maintain 2 pointers one at left and right. We are interested to achieve maximum area which is product of
9+
length and width.Also, to form a container,between 2 heights, only the lowest length of rod can be considered
10+
as the rest will overflow.So, we compare and consider the length accordingly. Width can be computed by the
11+
difference of indices. We move the left pointer if the left rod's height is small, as we want to maximize
12+
area, if not, we decrement right pointer. This way, we can achieve max area.
13+
*/
14+
class Solution {
15+
public int maxArea(int[] height) {
16+
int left = 0 , right = height.length - 1;
17+
int maxArea = 0;
18+
while(left < right) {
19+
int width = right - left;
20+
int length = 0;
21+
if(height[left] < height[right]) {
22+
length = height[left];
23+
left++;
24+
}
25+
else {
26+
length = height[right];
27+
right--;
28+
}
29+
maxArea = Math.max(maxArea, length * width);
30+
}
31+
return maxArea;
32+
}
33+
}

0 commit comments

Comments
 (0)