Type:medium
Given?n?non-negative integers?a1,?a2, ...,?an?, where each represents a point at coordinate (i,?ai).?n?vertical lines are drawn such that the two endpoints of line?i?is at (i,?ai) and (i, 0). Find two lines, which together with x-axis forms a container, such that the container contains the most water.
Note:?You may not slant the container and?n?is at least 2.
The above vertical lines are represented by array [1,8,6,2,5,4,8,3,7]. In this case, the max area of water (blue section) the container can contain?is 49.
Example:
Input:[1,8,6,2,5,4,8,3,7]Output:49
水箱問題,給定一個vector數(shù)組胖腾,按順序將其數(shù)值畫在坐標軸上烟零。取其中兩個值的大小做水箱側邊瘪松,x軸為水箱底咸作,使得水箱容量最大锨阿。
本題使用暴力遍歷做法,水箱高度為兩個值中略小的值记罚,長度為兩個值在數(shù)組中的距離墅诡。程序運行時間比平均題解略久,但消耗內存小于99.72%題解桐智。
class Solution {
public:
? ? int maxArea(vector<int>& height) {
? ? ? ? int max_area = 0;
? ? ? ? int n = height.size();
? ? ? ? for(int i=0; i<n; i++){
? ? ? ? ? ? for(int j=i+1; j<n; j++){
? ? ? ? ? ? ? ? int temp = (j-i)*(min(height[i], height[j]));
? ? ? ? ? ? ? ? if(temp > max_area) max_area = temp;
? ? ? ? ? ? }
? ? ? ? }
? ? ? ? return max_area;
? ? }
};