您的位置:首页 > 其它

Leetcode - Largest Rectangle in Histogram

2018-02-06 00:00 302 查看
摘要: dynamic programming

This is the anwser from others, which basically is using a stack to store the indices of the array elements who are greater than the element whose index is currently at the top of the stack.

We walk over the input array height[i], if the current element is larger than the previous one, we push its index to the stack.

And if the current element is smaller than the previous one, we pop the top index out, and set maxArea = height[stk_popout_index] *( (i - 1) - stk_attop_index ) ;

public class Solution {
public int largestRectangleArea(int[] height) {
int len = height.length;
Stack<Integer> s = new Stack<Integer>();
int maxArea = 0;
for(int i = 0; i <= len; i++){
int h = (i == len ? 0 : height[i]);
if(s.isEmpty() || h >= height[s.peek()]){
s.push(i);
}else{
int tp = s.pop();
maxArea = Math.max(maxArea, height[tp] * (s.isEmpty() ? i : i - 1 - s.peek()));
i--;
}
}
return maxArea;
}
}

The key here is the 'i--;' line which makes the current element remains the same after it is used as the sign to indicate a round of area calculation. Once the value of the element indexed by the top of the stack is smaller than the current height[i], then finished the calculation and move on the next element. This is tricky.

below is my own solution using dynamic programming, where s[i] represents the maxArea value for first i+1 element in input array;

public static int largestRectangleHistogram(int[] arr) {
int max = 0;

int n = arr.length;
int[] s = new int
;

// base case;
s[0] = arr[0];
s[1] = Math.max(Math.min(arr[0],arr[1])*2,
Math.max(arr[0], arr[1]));

// recur case;
for (int i = 2; i<n; i++){
// largestRectangle if includes arr[i];
int temp = 0;
int currMin = arr[i];
for (int j = i; j>=0; j--){
if (arr[j] < currMin) currMin = arr[j];
if (temp < currMin * (i - j + 1)) temp = currMin * (i - j + 1);
}

// largestRectangle is the max of:
// 1) includes arr[i]
// 2) without arr[i]
s[i] = Math.max(temp, s[i-1]);
}

max = s[n-1];
return max;
}

In my solution, since there is a nested loop, the time complexity is O(n^2).
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: