LeetCode75——Day12

文章目录

一、题目

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 <= 105

0 <= height[i] <= 104

二、题解

双指针+贪心

cpp 复制代码
class Solution {
public:
    int maxArea(vector<int>& height) {
        int n = height.size();
        int left = 0,right = n - 1;
        int maxS = 0;
        while(left < right){
            int h1 = height[left];
            int h2 = height[right];
            int S = min(h1,h2) * (right - left);
            maxS = max(maxS,S);
            if(h1 > h2) right--;
            else left++;
        }
        return maxS;
    }
};
相关推荐
水木姚姚3 分钟前
VSCode 调试 C++ 之 cin 输入
c++·windows·vscode·开发工具·调试
AuroraWanderll7 分钟前
C++类和对象--访问限定符与封装-类的实例化与对象模型-this指针(二)
c语言·开发语言·数据结构·c++·算法
一只小bit7 分钟前
Qt Widget 控件介绍:覆盖常用属性及API
开发语言·c++·qt·命令模式·cpp
月明长歌10 分钟前
【码道初阶】LeetCode 622:设计循环队列:警惕 Rear() 方法中的“幽灵数据”陷阱
java·算法·leetcode·职场和发展
Dylan的码园11 分钟前
链表与LinkedList
java·数据结构·链表
mit6.82417 分钟前
博弈-翻转|hash<string>|smid
算法
代码游侠20 分钟前
复习——Linux 系统编程
linux·运维·c语言·学习·算法
Han.miracle26 分钟前
优选算法-005 有效三角形的个数(medium)
数据结构·算法·有效的三角形个数
yuuki23323326 分钟前
【C++】类和对象下
数据结构·c++·算法
huohuopro29 分钟前
结构体与链表
数据结构·算法·链表