标签:
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.
有n个非负数,代表n个隔水板的高度,现在求两个隔水板之间最大的容水量,也就是找一对隔水板,距离*min(两个隔水板高度)的最大值。
class Solution { public: int maxArea(vector<int>& height) { int length=height.size(); if(length<=1) return 0; int cap=0; for(int i=0;i<length-1;i++) { for(int j=i+1;j<length;j++) { if(min(height[i],height[j])*(j-i)>cap) cap=min(height[i],height[j])*(j-i); } } return cap; } };
class Solution { public: int maxArea(vector<int>& height) { int length=height.size(); if(length<=1) return 0; int cap=0; int left=0,right=length-1; while(left<right) { if(min(height[left],height[right])*(right-left)>cap) cap=min(height[left],height[right])*(right-left); if(height[left]<height[right]) left++; else right--; } return cap; } };
标签:
原文地址:http://blog.csdn.net/sinat_24520925/article/details/46425099