[LeetCode] Container With Most Water

简介: Well, an interesting problem. If you draw some examples on a white board and try to figure out the regularities, you may have noticed that the key to ...

Well, an interesting problem. If you draw some examples on a white board and try to figure out the regularities, you may have noticed that the key to solving this problem is to use two pointers, one starting from the left end and the other starting from the right end. We compute an area for one configuration of the two pointers. Then we need to move them. If the left pointer has lower height, then we know it must be moved to one point with larger height in the right to make it possible for the area to increase. For the right pointer, the case is similar.

The following code is not well optimized, but being pretty short :-)

 1 class Solution {
 2 public:
 3     int maxArea(vector<int> &height) {
 4         int l = 0, r = height.size() - 1, area = 0;
 5         while(l < r) {
 6             area = max(area, min(height[r], height[l]) * (r - l));  
 7             height[l] <= height[r] ? l++ : r--;
 8         }
 9         return area;
10     }
11 };

You may avoid unnecessary checks by moving the left and right pointers to another place with larger height. However, the following code runs slower than the above one...

 1 class Solution {
 2 public:
 3     int maxArea(vector<int> &height) {
 4         int l = 0, r = height.size() - 1, area = 0;
 5         while(l < r) {
 6             int h = min(height[l], height[r]), w = r - l;
 7             area = max(area, h * w);  
 8             while (height[l] <= h && l < r) l++;
 9             while (height[r] <= h && r > l) r--;
10         }
11         return area;
12     }
13 };

Since the problem is not that hard, you may be required to think more, such at its time complexity. Could you prove that it runs in O(n) time? Well, this link has a very clever proof.

目录
相关文章
|
5月前
|
人工智能 容器
Leetcode 11. Container With Most Water
题目可以这么理解,在i位置有条高为ai的竖线,让你选出两台竖线构成一个容器,使得该容器装的水最多,注意容器不能倾斜。
25 3
|
数据库
LeetCode(数据库)- The Airport With the Most Traffic
LeetCode(数据库)- The Airport With the Most Traffic
104 0
|
容器
Leetcode-Medium 11. Container With Most Water
Leetcode-Medium 11. Container With Most Water
77 0
Leetcode-Medium 11. Container With Most Water
|
人工智能 算法 容器
leetcode 11 Container with Most Water
1.题目描述 Given n non-negative integers a1, a2, ..., an, where each represents a point at coordinate (i, ai).
1296 0
|
容器 人工智能
[LeetCode]--11. 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).
1094 0

热门文章

最新文章