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.
这个需要证明贪心算法的正确性
class Solution {
public:
int maxArea(vector<int> &height) {
int len = height.size();
int left = 0 ;
int right = len-1;
int max = 0 ;
while(left<right)
{
int temp = (right - left) * (height[left] < height[right] ? height[left] :height[right]);
max = max > temp ? max :temp;
if(height[left] > height[right])
right--;
else
left ++;
}
return max;
}
};
posted on 2014-04-15 16:57 pengyu2003 阅读(154) 评论(0) 收藏 举报
浙公网安备 33010602011771号