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.
首先,将两条线设为第一条和最后一条,此时的宽度是最大的。若以后的容器大于这个,只能是高度更高,所以可以更新短的那根线,若第一根线短,则向前推进,只有遇到更高的线时才需要重新计算;若短的是第二根线,则向后推进,遇到更高的线时更新
#include <algorithm> #include <iostream> #include <vector> using namespace std; class Solution { public: int maxArea(vector<int>& height) { int maxArea=0; int i=0; int j=height.size()-1; int h=0; while(i<j) { h=min(height[i],height[j]); maxArea=max(maxArea,h*(j-i)); cout<<maxArea<<endl; while(height[i]<=h&&i<j) i++; while(height[j]<=h&&i<j) j--; } return maxArea; } }; int main() { Solution sl1; vector<int> vec{1,2,3,6,5}; cout<<sl1.maxArea(vec)<<endl; }