Skip to content

Commit 66efb9f

Browse files
authored
Create container_with_most_water.md
1 parent 4c0bd6a commit 66efb9f

File tree

1 file changed

+38
-0
lines changed

1 file changed

+38
-0
lines changed

container_with_most_water.md

Lines changed: 38 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,38 @@
1+
# Container With Most Water
2+
## Problem
3+
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.
4+
5+
Note: You may not slant the container and n is at least 2
6+
## 问题分析
7+
这问题问的不清楚啊,不试一下的话都不知道最后要返回什么</br>
8+
最终要返回的是area</br>
9+
这个题一般是要遍历所有的组合,用一个max做比较,返回遍历完后的max;</br>
10+
但是这样很麻烦,时间复杂度也大,总结一下,我们发现,假设最终的两个高度为i,j&&i<j,那么j之后的高度一定都比a[j]小,同理,i之前的高度一定都比a[i]小</br>
11+
## 解题思路
12+
从两端开始遍历,不断更新端点值(若前一个高,则从后一个往前找大的值,否则从前一个从后找大的值);比较当前area值与max值,最终返回最终的max值
13+
## 代码实现
14+
```ruby
15+
int maxArea(int* height, int heightSize) {
16+
int max=0,area;
17+
int i=0,j=heightSize-1;
18+
while(i<j)
19+
{
20+
area=(height[i]<height[j]?height[i]:height[j])*(j-i);
21+
max=max>area?max:area;
22+
if(height[i]<height[j])
23+
{
24+
int k=i;
25+
while(i<j && height[i]<=height[k])
26+
i++;
27+
}
28+
else{
29+
int k=j;
30+
while(i<j && height[j]<=height[k])
31+
j--;
32+
}
33+
}
34+
return max;
35+
}
36+
```
37+
## 总结
38+
这种不断更新端点值的算法之前也经常用,能记得的有 sum 的一系列问题(3sum,3sum closest,4sum等);二分查找法也是这样,不断更新端点值来求中间值

0 commit comments

Comments
 (0)