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;
    }
};
相关推荐
java修仙传几秒前
力扣hot100:旋转排序数组中找目标值
算法·leetcode·职场和发展
式5162 分钟前
量子力学基础(二)狄拉克符号与复数向量空间
人工智能·算法·机器学习
k***921612 分钟前
【Linux】进程概念(六):地址空间核心机制
linux·运维·算法
xu_yule14 分钟前
算法基础-字符串哈希
算法·哈希算法·散列表
李白同学16 分钟前
Linux:调试器-gdb/cgdb使用
linux·服务器·c语言·c++
lixzest17 分钟前
C++中经常用的头文件介绍
数据结构·c++·算法
白昼流星!18 分钟前
C++内存四区与new操作符详解
开发语言·c++
十五年专注C++开发19 分钟前
标准C++操作文件方法总结
开发语言·c++·文件操作·ifstream
保持低旋律节奏22 分钟前
linux——进程调度(时间片+优先级轮转调度算法O(1))
linux·运维·算法
虾..30 分钟前
Linux 进程池小程序
linux·c++·小程序