友情支持
如果您觉得这个笔记对您有所帮助,看在D瓜哥码这么多字的辛苦上,请友情支持一下,D瓜哥感激不尽,😜
有些打赏的朋友希望可以加个好友,欢迎关注D 瓜哥的微信公众号,这样就可以通过公众号的回复直接给我发信息。
公众号的微信号是: jikerizhi 。因为众所周知的原因,有时图片加载不出来。 如果图片加载不出来可以直接通过搜索微信号来查找我的公众号。 |
11. Container With Most Water
Given n non-negative integers a1, a2, …, a~n ~, 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.
[.small]#The above vertical lines are represented by array [1,8,6,2,5,4,8,3,7]. In this case, the max area of water (blue section) the container can contain is 49. #
Example:
Input: [1,8,6,2,5,4,8,3,7] Output: 49
解题分析
双指针左右夹逼,保留高个,移动低个。
这里有个疑问,不考虑中间
-
一刷
-
二刷
-
三刷
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
/**
* @author D瓜哥 · https://www.diguage.com
* @since 2018-07-13
*/
public static int maxArea(int[] height) {
int result = 0;
int left = 0, right = height.length - 1;
while (left < right) {
int area = Math.min(height[left], height[right]) * (right - left);
result = Math.max(result, area);
if (height[left] < height[right]) {
left++;
} else {
right--;
}
}
return result;
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
/**
* @author D瓜哥 · https://www.diguage.com
* @since 2024-08-15 19:54:27
*/
public static int maxArea(int[] height) {
int left = 0, right = height.length - 1;
int result = 0;
while (left < right) {
if (height[left] < height[right]) {
result = Math.max(result, height[left] * (right - left));
left++;
} else {
result = Math.max(result, height[right] * (right - left));
right--;
}
}
return result;
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
/**
* @author D瓜哥 · https://www.diguage.com
* @since 2024-09-16 19:38:05
*/
public int maxArea(int[] height) {
int result = 0;
int left = 0, right = height.length - 1;
while (left < right) {
result = Math.max(result,
Math.min(height[left], height[right]) * (right - left - 1));
if (height[left] < height[right]) {
left++;
} else {
right--;
}
}
return result;
}