标签:unit return ret style call https www str eve
84. Largest Rectangle in Histogram https://www.youtube.com/watch?v=KkJrGxuQtYo&t=129s 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. Input: [2,1,5,6,2,3] Output: 10 Solution 1 : time o(n^ 2) // loop thru from left to right // if the height is increasing, keep i++; // and once the height is decreasing, we look back at the // columns and calculate every area // formula is length * min(heights) // use a var called res to update the res // after done with that, i++ // if the height is decreasing again, we do the same as above // check if the next one is increasing, or decreasing // if increasing , keep going // if dereasing or hit the end, reflect and calculate prev areas class Solution { public int largestRectangleArea(int[] heights) { if(heights == null || heights.length == 0) return 0; int res = 0; for(int i = 0; i < heights.length; i++){ // if hit the end or the next height is decreasing if(i == heights.length - 1 || heights[i] > heights[i + 1]){ int minHeight = heights[i]; for(int j = i; j >= 0; j--){ minHeight = Math.min(minHeight, heights[j]); int area = (i - j + 1) * minHeight; res = Math.max(res, area); } } } return res; } } Solution 2 : using stack , time o(n)
84. Largest Rectangle in Histogram
标签:unit return ret style call https www str eve
原文地址:https://www.cnblogs.com/tobeabetterpig/p/9682510.html