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 17
17
class Solution {
18
18
public:
19
19
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-- ;
28
35
}
29
36
30
- return area ;
37
+ return maxArea ;
31
38
}
32
39
};
You can’t perform that action at this time.
0 commit comments