标签:
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.
题意:x轴上的n条垂直线,求类似木板盛水的最大值
思路:双指针加贪心,每次对当前的l和r围成的水池计算面积,然后对于更新l或r的话,就看curL和curR的大小,贪心的来看的话,如果curL<curR的话,那么将l指针向右移动显然是比较好的,移动到的位置取决于是否能找到更大的curL,至于另外一种情况类似
class Solution { public: int maxArea(vector<int> &height) { int l, r; int len = height.size() - 1; l = 0, r = len; int curL = height[l]; int curR = height[r]; int Max = 0; while (l < r) { int tmp = min(curL, curR) * (r - l); if (Max < tmp) Max = tmp; if (curL > curR) { while(l < r && curR >= height[r]) r--; if (l < r) curR = height[r]; } else { while (l < r && curL >= height[l]) l++; if (l < r) curL = height[l]; } } return Max; } };
LeetCode Container With Most Water
标签:
原文地址:http://blog.csdn.net/u011345136/article/details/42815387