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;
    }
};
相关推荐
木井巳2 分钟前
【笔试强训】Day1
java·算法
leiming64 分钟前
巧用 FreeRTOS 任务通知作“邮箱”:NeoPixel 灯环控制实战
java·前端·算法
老四啊laosi4 分钟前
[双指针] 4. 力扣--盛最多水的容器
算法·leetcode·装水最多的容器
wanderist.6 分钟前
高维矩阵的压维存储和高维差分
c++·算法·蓝桥杯
迈巴赫车主14 分钟前
蓝桥杯192.等差数列java
java·数据结构·算法·职场和发展·蓝桥杯
chase。24 分钟前
【学习笔记】从经典算法到通用神经运动规划器
笔记·学习·算法
王璐WL28 分钟前
【C++】经典且易错的题
c++
feasibility.31 分钟前
OpenCV图像滤波算法应用:常见滤波器的原理与效果对比(含c++/python代码与中文显示)
c++·opencv·算法
老虎062733 分钟前
数据结构09(Java)-- 二分查找模板
java·开发语言·数据结构
Rabitebla37 分钟前
快速排序(QuickSort)完全指南 —— 从原理到工业级优化
c语言·数据结构·c++·算法·github