LeetCode //C - 11. Container With Most Water
2023-12-21 08:42:46
11. Container With Most Water
You are given an integer array height of length n. There are n vertical lines drawn such that the two endpoints of the ith line are (i, 0) and (i, height[i]).
Find two lines that together with the x-axis form a container, such that the container contains the most water.
Return the maximum amount of water a container can store.
Notice that you may not slant the container.
?
Example 1:
Input: height = [1,8,6,2,5,4,8,3,7]
Output: 49
Explanation: 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 2:
Input: height = [1,1]
Output: 1
Constraints:
- n == height.length
- 2 < = n < = 1 0 5 2 <= n <= 10^5 2<=n<=105
- 0 < = h e i g h t [ i ] < = 1 0 4 0 <= height[i] <= 10^4 0<=height[i]<=104
From: LeetCode
Link: 11. Container With Most Water
Solution:
Ideas:
- We start with two pointers, one at the beginning (left) and one at the end (right) of the array.
- We calculate the area formed between the two pointers and compare it to the maximum area found so far.
- We move the pointer that points to the shorter line inward, as this could potentially increase the area.
- We continue this process until the two pointers meet.
- We return the maximum area found.
Code:
int maxArea(int* height, int heightSize) {
int max_area = 0;
int left = 0;
int right = heightSize - 1;
while (left < right) {
int width = right - left;
int current_height = height[left] < height[right] ? height[left] : height[right];
int current_area = width * current_height;
max_area = current_area > max_area ? current_area : max_area;
if (height[left] < height[right]) {
left++;
} else {
right--;
}
}
return max_area;
}
文章来源:https://blog.csdn.net/navicheung/article/details/135121618
本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。 如若内容造成侵权/违法违规/事实不符,请联系我的编程经验分享网邮箱:veading@qq.com进行投诉反馈,一经查实,立即删除!
本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。 如若内容造成侵权/违法违规/事实不符,请联系我的编程经验分享网邮箱:veading@qq.com进行投诉反馈,一经查实,立即删除!