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.
与42. Trapping Rain Water 类似,两条垂直的线和X轴组成一个容器,灌水多少不仅与两个柱子的高度有关,也与两个柱子的距离有关,公式:S(i,j) = min(ai, aj) * (j-i),容器不能倾斜,求容纳最多水的两个线组合。
用暴力搜索Brute Force, Time: O(n2)会超时。
使用双指针two pointers。 定义left,right两个指针,两指针相遇循环结束。何时移动左右指针呢,保留较高的柱子,移动较矮的柱子。
Time complexity: O(n), Space complexity: O(1)
Java:
class Solution { public int maxArea(int[] height) { int l = 0; int r = height.length - 1; int ans = 0; while (l < r) { int h = Math.min(height[l], height[r]); ans = Math.max(ans, h * (r - l)); if (height[l] < height[r]) ++l; else --r; } return ans; } }
Python:
class Solution: def maxArea(self, height): max_area, i, j = 0, 0, len(height) - 1 while i < j: max_area = max(max_area, min(height[i], height[j]) * (j - i)) if height[i] < height[j]: i += 1 else: j -= 1 return max_area
C++:
class Solution { public: int maxArea(const vector<int>& height) { int ans = 0; int l = 0; int r = height.size() - 1; while (l < r) { int h = min(height[l], height[r]); ans = max(ans, h * (r - l)); if (height[l] < height[r]) ++l; else --r; } return ans; } };
类似题目:
[LeetCode] 42. Trapping Rain Water 收集雨水