当前位置:网站首页>[Li Kou brush questions] 11 Container holding the most water //42 Rain water connection
[Li Kou brush questions] 11 Container holding the most water //42 Rain water connection
2022-06-26 16:21:00 【Li xiaoenzi】
subject :
Given a length of n Array of integers for height . Yes n Vertical line , The first i The two ends of the line are (i, 0) and (i, height[i]) .
Find two of them , Make them x A container of shafts can hold the most water .
Return the maximum amount of water that the container can store .
explain : You can't tilt the container .
source : Power button (LeetCode)
link :https://leetcode.cn/problems/container-with-most-water
When I saw this problem, the first thing in my mind was to solve it with monotone stack : Because I want to seek the maximum , Find two wires , Use monotone decreasing stack to judge ... Make a judgment when entering the stack , If it's bigger than the top of the stack , Then the top elements of the stack will pop up continuously , The result of the calculation is ; If it is smaller than the top element of the stack, add it directly ; Until the end of the traversal , The whole stack is monotonically decreasing , Then they are processed together until the top element of the stack is empty .( In the process, I recorded the elements at the bottom of the stack )
class Solution {
public int maxArea(int[] height) {
// Monotone stack problem , Monotonically decreasing stacks
// What holds the most water depends on the short side , Not the long side
// So make a judgment when entering the stack , If it's bigger than the top of the stack , Then the top elements of the stack will pop up continuously , Calculate the product from this edge to the edge of the top element of the stack , Find the maximum , Then add this edge to the stack
// If it is smaller than the top element of the stack, it is directly added to the stack
// Finally, handle the elements in the stack , Until the stack element is empty
Stack<Integer> stack = new Stack<Integer>();
int res = 0;
// Save the maximum stack bottom element
int maxLow = 0;
for(int i = 0;i < height.length;i++){
if(stack.size() == 0) {
stack.push(i);
maxLow = i;
}
if(stack.size() != 0 && height[stack.peek()] >= height[i]) stack.push(i);
// If the element is larger than the top of the stack , Then the calculation results of the elements at the top of the stack are continuously popped up
// Notice why while
while(stack.size() != 0 && height[stack.peek()] < height[i]){
res = Math.max(res,height[stack.peek()]*(i-stack.pop()));
}
// Add this element to the stack
if(stack.size() == 0) maxLow = i;
stack.push(i);
}
// Finally, the remaining elements in the stack are processed , The top element of the stack is the smallest element , The bottom of the stack is the largest element
while(stack.size() != 0){
res = Math.max(res,height[stack.peek()]*(stack.pop()-maxLow));
}
return res;
}
}Then I found out that it was only 24 A use case :

such as [1,2,1] Such use cases cannot pass , exactly , because 1 After adding to the stack , Judge 2 When , because 2 Than 1 Big , Will pop up 1, Then the monotonically decreasing stack starts from 2 Start , Obviously this is wrong , The result should be the beginning 1 To the end 1.
I haven't figured out how to solve it with monotone stack ... Because this way of thinking is really wrong , There seems to be a similar problem , I'll update it later ......
Then I looked at the analysis , The answer is to use double pointers .
In each state , Whether the long board or the short board narrows one grid to the middle , Will cause the sink Bottom edge width -1−1 shorter :
① If inward Move the short board , The short board of the sink min(h[i], h[j])min(h[i],h[j]) May be bigger , Therefore, the area of the next tank may increase .
② If inward Move the long board , The short board of the sink min(h[i], h[j])min(h[i],h[j]) Constant or smaller , So the area of the next sink must be smaller .
therefore , Initialize the double pointer to separate the left and right ends of the sink , Move the short board inward one grid in each cycle , And update the maximum area , Until the two pointers meet and jump out ; You can get the maximum area .
Code :
class Solution {
public int maxArea(int[] height) {
int i = 0, j = height.length - 1, res = 0;
while(i < j) {
res = height[i] < height[j] ?
Math.max(res, (j - i) * height[i++]):
Math.max(res, (j - i) * height[j--]);
}
return res;
}
}anthracene ... Really good concise code ...
42. Rainwater collection

Monotonically decreasing stack implementation :
class Solution {
public int trap(int[] height) {
// Monotonically decreasing stacks
Stack<Integer> stack = new Stack<Integer>();
int res = 0;
for(int i = 0;i < height.length;i++){
if(stack.size() == 0) {
stack.push(i);
}
if(stack.size() != 0 && height[stack.peek()] >= height[i]) stack.push(i);
// If the element is larger than the top of the stack , Then the calculation results of the elements at the top of the stack are continuously popped up
// Notice why while
while(stack.size() != 0 && height[stack.peek()] < height[i]){
int mid = stack.pop();// The middle element
if(stack.size() != 0){
int h = Math.min(height[stack.peek()],height[i]) - height[mid];
int w = i - stack.peek() - 1;// Note that only the width in the middle , So we need to reduce 1
res += h * w;
}
}
// Add this element to the stack
stack.push(i);
}
return res;
}
}The following one I use monotone decrement stack will not make mistakes , Because I only need to find the left and right boundaries of the containers that can receive water at present , It has nothing to do with the columns in front , And the question above , It may be infinite between two short edges on the boundary , Using the monotone stack to judge and pop up elements will have problems .
边栏推荐
- 【207】Apache崩溃的几个很可能的原因,apache崩溃几个
- 6 custom layer
- 基於Kubebuilder開發Operator(入門使用)
- NFT transaction principle analysis (2)
- LeetCode 单周赛298,前三题
- H5 close the current page, including wechat browser (with source code)
- Swiftui retrieves the missing list view animation
- How to create your own NFT (polygon) on opensea
- 基于Kubebuilder开发Operator(入门使用)
- 6 自定义层
猜你喜欢

Big talk Domain Driven Design -- presentation layer and others

【力扣刷题】二分查找:4. 寻找两个正序数组的中位数

JS教程之使用 ElectronJS、VueJS、SQLite 和 Sequelize ORM 从 A 到 Z 创建多对多 CRUD 应用程序

今年高考英语AI得分134,复旦武大校友这项研究有点意思

"C language" question set of ⑩

振动式液量检测装置

了解下常见的函数式接口

心情不好,我就这样写代码
![[graduation season] a word for graduates: the sky is high enough for birds to fly, and the sea is wide enough for fish to leap](/img/b6/21e51fa7f79d4a4b950f061703f0fb.png)
[graduation season] a word for graduates: the sky is high enough for birds to fly, and the sea is wide enough for fish to leap

TCP拥塞控制详解 | 1. 概述
随机推荐
若依微服务特殊字符串被过滤的解决办法
[207] several possible causes of Apache crash
1-12Vmware新增SSH功能
长安链交易防重之布谷鸟过滤器
4 custom model training
请指教同花顺软件究竟是什么?网上开户是否安全么?
Tencent Peking University's sparse large model training acceleration program het was selected into the VLDB of the international summit
Binary array command of redis
用Attention和微调BERT进行自然语言推断-PyTorch
[chat in 5] eight years after graduation, I have been pursuing my dream
《软件工程》期末重点复习笔记
[机缘参悟-31]:鬼谷子-抵巇[xī]篇-危机是危险与机会并存
redis的二进制数组命令
手写数字体识别,用保存的模型跑自己的图片
基於Kubebuilder開發Operator(入門使用)
Pybullet robot simulation environment construction 5 Robot pose visualization
7 自定义损失函数
The first batch in the industry! Tencent cloud security and privacy computing products based on angel powerfl passed CFCA evaluation
理想路径问题
3 keras版本模型训练