题目描述
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 and n is at least 2.
- 解法1
两个方向的遍历,例如对于i = 0 from n-1,只考虑height[j] >= height[i]的情况,那么j满足:height[j] >= height[i], 而且j尽可能大。即只考虑容器左边低,右边高的情况。反向同理。采用预处理可以达到O(n log n)。 解法2
思考一下各种有可能的结果区间:[l_0, r_0], [l_1, r_1]…,有一个关键特点:如果区间x包含了区间y,即l_x <= l_y && r_y <= r_x,那么此时,height[l_y] > Min && height[r_y] > Min, Min = min(l_x, r_x)。
有了这个特点,那么对于区间[0, n-1]来说,就可以找最长的真子区间[a, b],显然不会存在区间:边界在(0, a) U (b, n-1)中。然后对于子区间[a, b],递归即可。复杂度为O(n)class Solution { public: int maxArea(vector<int>& height) { int i = 0, j = height.size() - 1, ans = 0; while (i < j) { int Min = std::min(height[i], height[j]); ans = std::max(ans, Min * (j - i)); while (height[i] <= Min && i < j) i++; while (height[j] <= Min && i < j) j--; } return ans; } };