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;
}
}

最新文章

  1. iOS所有常见证书,appID,Provisioning Profiles配置说明及制作图文教程
  2. Tomcat部署web项目,虚拟目录,上下文(Context),WEB-INF,web.xml,servlet,404
  3. sql 内连接和外链接
  4. Ignoring Extra Elements in mongoDB C# Driver
  5. [原创]java WEB学习笔记61:Struts2学习之路--通用标签 property,uri,param,set,push,if-else,itertor,sort,date,a标签等
  6. Redis各种数据结构内存占用测试
  7. ASP.NET中Json的处理
  8. 与IO相关的等待事件troubleshooting-系列5
  9. Codeforces Round #277.5 (Div. 2) --E. Hiking (01分数规划)
  10. ionic3 自动创建启动背景splash以及图标icon
  11. angular开发环境配置全套教程
  12. WIN10 困扰多时的屏幕亮度 终于可以调节了-完美 -更新2018年2月28日
  13. 8. American Friendship 美国式的友谊
  14. Zookeeper客户端Curator---Getting Started
  15. C语言强化——数组
  16. 数据绑定到ADO.NET
  17. linux命令-每天一点进步
  18. JAVA array,map 转 json 字符串
  19. 《LeetBook》leetcode题解(4): Median of Two Sorted Arrays[H]——两个有序数组中值问题
  20. Gluon Data API

热门文章

  1. LeetCode82----删除排序链表中的重复元素 II
  2. 10、kubernetes之RBAC认证
  3. leetcode 31下一个排列
  4. gradle 离线模式offline 用法
  5. Windows下C/C++内存泄露检测机制
  6. 阶段3 2.Spring_09.JdbcTemplate的基本使用_5 JdbcTemplate在spring的ioc中使用
  7. 阶段3 2.Spring_07.银行转账案例_1 今日课程内容介绍
  8. 阶段3 2.Spring_05.基于XML的IOC的案例1_1 基于XML的IOC的案例-案例准备
  9. When specified, &quot;proxy&quot; in package.json must be a string.
  10. Cocos2d-X多线程(2) 线程的互斥量std::mutex和线程锁