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;
    }
};
相关推荐
Live&&learn26 分钟前
算法训练-数据结构
数据结构·算法·leetcode
胡萝卜3.01 小时前
掌握C++ map:高效键值对操作指南
开发语言·数据结构·c++·人工智能·map
松岛雾奈.2302 小时前
机器学习--PCA降维算法
人工智能·算法·机器学习
电子_咸鱼2 小时前
【STL string 全解析:接口详解、测试实战与模拟实现】
开发语言·c++·vscode·python·算法·leetcode
sweet丶2 小时前
适合iOS开发的一种缓存策略YYCache库 的原理
算法·架构
是宇写的啊3 小时前
算法—滑动窗口
算法
风筝在晴天搁浅3 小时前
代码随想录 509.斐波那契数
数据结构·算法
落落落sss3 小时前
java实现排序
java·数据结构·算法
fei_sun4 小时前
【数据结构】2018年真题
数据结构
limenga1024 小时前
支持向量机(SVM)深度解析:理解最大间隔原理
算法·机器学习·支持向量机