Container with most water
GivenNnon-negative integersa1 ,a2 , ...,an , where each represents a point at coordinate (I,ai ).NVertical lines is drawn such that the both endpoints of lineIis at (I,ai ) and (I, 0). Find lines, which together with X-axis forms a container, such that the container contains the most water.
Note:you may not slant the container.
Analysis reference here, the author explains it in detail.
Class Solution {public: int. maxarea (vector<int> &height) { int left = 0,right = Height.size () -1,area = 0 ; while (left < right) { area = max (Area,min (Height[left],height[right]) * (right-left));//Current Location if ( Height[left] < Height[right]) { int k = left; while (K < right && Height[k] <= height[left]) ++k;//find the next position left = k; } else { int k = right; while (K > left && height[k] <= height[right])--k;//Find Next position right = k; } } return area; }};
Trapping Rain Water
given n non-negative integers representing an elevation map where The width of each bar was 1, compute how much water it was able to trap after raining.
For example,
Given [0,1,0,2,1,0,1,3,2,1,2,1]
, return 6
.
The above elevation map is represented by array [0,1,0,2,1,0,1,3,2,1,2,1]. In this case, 6 units of the Rain Water (blue section) is being trapped. Thanks Marcos for contributing this image!
See here, the author explained in detail
Class Solution {public: int trap (int a[], int n) { vector<int> leftmostheight (n,0), Rightmostheight ( n,0); int mostheiht = 0,i,area = 0; for (i = 0;i < N;++i) { Leftmostheight[i] = mostheiht;//to the left of the maximum height mostheiht = max (Mostheiht,a[i]); } mostheiht = 0; for (i = n-1;i >= 0;--i) { Rightmostheight[i] = mostheiht;//to the right of the maximum height mostheiht = max (Mostheiht,a[i]); c14/>} for (i = 0;i < N;++i) { int a = min (Leftmostheight[i],rightmostheight[i])-a[i];//The current height of the if (a > 0) area + = A; } return area; }};
There are also two similar topics, all of which are related to histograms, see here
Leetcode container with the most water and trapping Rain water