At the beginning of the violent settlement, the time did not pass
1 classSolution {2 Public:3 intMaxarea (vector<int>&height) {4 intMaxarea=0, eacharea=0;5 if(Height.size () <2)returnMaxarea;6 for(intI=0; I)7 for(intj=i+1; J)8 {9Eacharea= (Height[i]>height[j]?height[j]:height[i]) * (J-i);Ten if(Eacharea>maxarea) maxarea=Eacharea; One } A returnMaxarea; - } -};
Later to see the great God's explanation, found that the problem principle is super simple:
The so-called container can be regarded as a rectangular box, we first put the integer capacity as one side of the length, the two shortest high as the other side of the long side, then get a rectangular area. Later to find larger than this area, when the side of the rectangle shrinks, then only the other side of the length of the larger, the overall area is likely to become larger. Therefore, when the container from two to the middle of the narrowing, you have to find the shortest side than the two long-test. So the last time complexity is O (n)
Here's the code:
1 classSolution {2 Public:3 intMaxarea (vector<int>&height) {4 intWater=0, H;5 intI=0, J=height.size ()-1;6 while(i<j)7 {8H=min (height[i],height[j]);9 if(wateri);Ten while(height[i]<=h && i<j) i++; One while(height[j]<=h && i<j) j--; A } - returnwater; - } the -};
Container with most water