85. Maximal Rectangle (JAVA)
2024-09-01 13:53:22
Given n non-negative integers representing the histogram's bar height where the width of each bar is 1, find the area of largest rectangle in the histogram.
Above is a histogram where width of each bar is 1, given height =[2,1,5,6,2,3]
.
The largest rectangle is shown in the shaded area, which has area =10
unit.
Example:
Input: [2,1,5,6,2,3]
Output: 10
84. Largest Rectangle in Histogram的升级版: 按行按列分别做动态规划
class Solution {
public int maximalRectangle(char[][] matrix) {
if(matrix.length == 0 ) return 0; int width = matrix[0].length;
int height = matrix.length;
int maxArea = 0;
int area; //按列动态规划,求出到此位置最多连续为1的次数
int[][] dp = new int[height][width];
for(int i = 0; i < width; i++){
for(int j = 0; j < height; j++){
dp[j][i] = matrix[j][i] - '0';
if(matrix[j][i] == '1' && j > 0){
dp[j][i] += dp[j-1][i];
}
}
} //按行动态规划,求出最大面积
for(int i = 0; i < height; i++){
area = largestRectangleArea(dp[i]);
if(area > maxArea) maxArea = area;
}
return maxArea;
} public int largestRectangleArea(int[] heights) {
Stack<Integer> st = new Stack<Integer>();
if(heights.length == 0) return 0; int leftIndex;
int topIndex;
int area;
int maxArea = 0;
int i = 0;
while(i < heights.length){
if(st.empty() || heights[i] >= heights[st.peek()]){
st.push(i);
i++;
}
else{
topIndex = st.peek();
st.pop();
leftIndex = st.empty()?0:st.peek()+1; //如果是空,说明从头开始的所有高度都比heights[topIndex]高
area = ((i-1)-leftIndex + 1) * heights[topIndex];
if(area > maxArea) maxArea = area;
}
}
while(!st.empty()){ //没有比栈顶元素小的元素让它出栈
topIndex = st.peek();
st.pop();
leftIndex = st.empty()?0:st.peek()+1;
area = ((i-1)-leftIndex + 1) * heights[topIndex];
if(area > maxArea) maxArea = area;
}
return maxArea;
}
}
最新文章
- iOS所有常见证书,appID,Provisioning Profiles配置说明及制作图文教程
- Tomcat部署web项目,虚拟目录,上下文(Context),WEB-INF,web.xml,servlet,404
- sql 内连接和外链接
- Ignoring Extra Elements in mongoDB C# Driver
- [原创]java WEB学习笔记61:Struts2学习之路--通用标签 property,uri,param,set,push,if-else,itertor,sort,date,a标签等
- Redis各种数据结构内存占用测试
- ASP.NET中Json的处理
- 与IO相关的等待事件troubleshooting-系列5
- Codeforces Round #277.5 (Div. 2) --E. Hiking (01分数规划)
- ionic3 自动创建启动背景splash以及图标icon
- angular开发环境配置全套教程
- WIN10 困扰多时的屏幕亮度 终于可以调节了-完美 -更新2018年2月28日
- 8. American Friendship 美国式的友谊
- Zookeeper客户端Curator---Getting Started
- C语言强化——数组
- 数据绑定到ADO.NET
- linux命令-每天一点进步
- JAVA array,map 转 json 字符串
- 《LeetBook》leetcode题解(4): Median of Two Sorted Arrays[H]——两个有序数组中值问题
- Gluon Data API
热门文章
- LeetCode82----删除排序链表中的重复元素 II
- 10、kubernetes之RBAC认证
- leetcode 31下一个排列
- gradle 离线模式offline 用法
- Windows下C/C++内存泄露检测机制
- 阶段3 2.Spring_09.JdbcTemplate的基本使用_5 JdbcTemplate在spring的ioc中使用
- 阶段3 2.Spring_07.银行转账案例_1 今日课程内容介绍
- 阶段3 2.Spring_05.基于XML的IOC的案例1_1 基于XML的IOC的案例-案例准备
- When specified, ";proxy"; in package.json must be a string.
- Cocos2d-X多线程(2) 线程的互斥量std::mutex和线程锁