Skip to content

Commit f610c45

Browse files
committed
Add comments for "Container With Most Water"
1 parent 990d56f commit f610c45

File tree

1 file changed

+16
-9
lines changed

1 file changed

+16
-9
lines changed

src/containerWithMostWater/containerWithMostWater.cpp

Lines changed: 16 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -17,16 +17,23 @@
1717
class Solution {
1818
public:
1919
int maxArea(vector<int> &height) {
20-
int area = 0;
21-
int i = 0;
22-
int j = height.size()-1;
23-
24-
while(i<j){
25-
int a = (j-i)* (height[i]>height[j] ? height[j] : height[i]);
26-
area = a>area ? a : area;
27-
height[i]>height[j] ? j-- : i++;
20+
21+
int maxArea = 0;
22+
// two pointers scan from two sides to middle
23+
int left = 0;
24+
int right = height.size()-1;
25+
26+
int area;
27+
while ( left < right ){
28+
//calculate the area
29+
area = (right - left) * ( height[left] < height[right] ? height[left] : height[right]);
30+
//tracking the maxium area
31+
maxArea = area > maxArea ? area : maxArea;
32+
// because the area is decided by the shorter edge
33+
// so we increase the area is to increase the shorter edge
34+
height[left] < height[right] ? left++ : right-- ;
2835
}
2936

30-
return area;
37+
return maxArea;
3138
}
3239
};

0 commit comments

Comments
 (0)