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;
    }
};
相关推荐
ytttr8731 小时前
隐马尔可夫模型(HMM)MATLAB实现范例
开发语言·算法·matlab
AlenTech2 小时前
160. 相交链表 - 力扣(LeetCode)
数据结构·leetcode·链表
点云SLAM2 小时前
凸优化(Convex Optimization)理论(1)
人工智能·算法·slam·数学原理·凸优化·数值优化理论·机器人应用
会周易的程序员2 小时前
多模态AI 基于工业级编译技术的PLC数据结构解析与映射工具
数据结构·c++·人工智能·单例模式·信息可视化·架构
jz_ddk2 小时前
[学习] 卫星导航的码相位与载波相位计算
学习·算法·gps·gnss·北斗
放荡不羁的野指针2 小时前
leetcode150题-动态规划
算法·动态规划
sin_hielo2 小时前
leetcode 1161(BFS)
数据结构·算法·leetcode
一起努力啊~2 小时前
算法刷题-二分查找
java·数据结构·算法
水月wwww3 小时前
【算法设计】动态规划
算法·动态规划
码农水水4 小时前
小红书Java面试被问:Online DDL的INSTANT、INPLACE、COPY算法差异
算法