Leetcode--84. 柱状图中最大的矩形
給定 n 個(gè)非負(fù)整數(shù),用來(lái)表示柱狀圖中各個(gè)柱子的高度。每個(gè)柱子彼此相鄰,且寬度為 1 。
求在該柱狀圖中,能夠勾勒出來(lái)的矩形的最大面積。
以上是柱狀圖的示例,其中每個(gè)柱子的寬度為 1,給定的高度為?[2,1,5,6,2,3]。
圖中陰影部分為所能勾勒出的最大矩形面積,其面積為?10?個(gè)單位。
?
示例:
輸入: [2,1,5,6,2,3]
輸出: 10
思路:
時(shí)間復(fù)雜度:o(n^2)
從i=0開始遍歷,每次都計(jì)算出以當(dāng)年位置為最后位置的各矩形面積并比較大小
例如本題,i=3時(shí),dp[3]=6
只包含當(dāng)前柱體的面積是6
向前遍歷,寬度加1,高度取二者中最小的? ?即2*5=10
繼續(xù)向前遍歷,寬度加1,高度取三者中最小,即3*1=3
繼續(xù)........即4*1=4
提交的代碼:
class Solution {
? ? public int largestRectangleArea(int[] heights) {
? ? ? ?if(heights.length==0)
? ? {
? ? ? ? return 0;
? ? }
?? ?int max=heights[0],x,y,t;
?? ?for(int i =0;i<heights.length;i++)
?? ?{
?? ??? ?x=0;
?? ??? ?y=heights[i];
?? ??? ?for(int j=i;j>=0;j--)
?? ??? ?{
?? ??? ??? ?x++;
?? ??? ??? ?y = Math.min(y, heights[j]);
?? ??? ??? ?t = x*y;
?? ??? ??? ?max = Math.max(max, t);
?? ??? ?}
?? ?}
?? ?return max;
? ? }
}
完整的代碼:
public class Solution84 {
public static int largestRectangleArea(int[] heights) {
?? ?if(heights.length==0)
? ? {
? ? ? ? return 0;
? ? }
?? ?int max=heights[0],x,y,t;
?? ?for(int i =0;i<heights.length;i++)
?? ?{
?? ??? ?x=0;
?? ??? ?y=heights[i];
?? ??? ?for(int j=i;j>=0;j--)
?? ??? ?{
?? ??? ??? ?x++;
?? ??? ??? ?y = Math.min(y, heights[j]);
?? ??? ??? ?t = x*y;
?? ??? ??? ?max = Math.max(max, t);
?? ??? ?}
?? ?}
?? ?return max;
? ? ? ??
? ? }
public static void main(String[] args)
{
?? ?int nums[] = {2,1,5,6,2,3};
?? ?System.out.println(largestRectangleArea(nums));
}
}
?
總結(jié)
以上是生活随笔為你收集整理的Leetcode--84. 柱状图中最大的矩形的全部?jī)?nèi)容,希望文章能夠幫你解決所遇到的問(wèn)題。
- 上一篇: java 开发环境的搭建
- 下一篇: AcWing:3.完全背包问题