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 and n is at least 2.
Example 1
1 | Input: [1,8,6,2,5,4,8,3,7] |
解题思路
初始时刻让两壁分别位于两端,然后不断缩小两壁距离。为使容量有可能增大,须将矮的一端换成更高的壁。
复杂度分析
- 时间复杂度:$O(n)$
- 空间复杂度:$O(1)$
代码
1 | int maxArea(vector<int>& height) { |