File tree Expand file tree Collapse file tree 1 file changed +16
-9
lines changed
src/containerWithMostWater Expand file tree Collapse file tree 1 file changed +16
-9
lines changed Original file line number Diff line number Diff line change 1717class Solution {
1818public:
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};
You can’t perform that action at this time.
0 commit comments