Container With Most Water
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.
using namespace std; #if 0 /* *最直观的比较方式 * 复杂度O(N^2) * 代码通不过 * */ class Solution{ public: int maxArea(vector<int> &height){ int n=height.size(); int i=0; int c_max=0; while(i<n){ for(int end=i+1;end<n;end++) c_max=max(c_max,(end-i)*min(height[end],height[i])); i++; } return c_max; } }; #endif /* *思路:虽然本题有两个变化量,距离和高度都在变,但是坐标i每次变化都是单位1。则只用顾虑高度变化。 * 虽然没有遍历完所有矩形。但能保证当前遍历的矩形在当前间距长度下,矩形面积一定是该距离下最大的。 * * */ class Solution{ public: int maxArea(vector<int> &height){ int end=height.size()-1; int start=0; int c_max=0; while(start<end){ c_max=max(c_max,(end-start)*min(height[end],height[start])); if(height[start]<=height[end]) start++; else end--; } return c_max; } };