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.
문제 풀이:
지난번에 풀었던 문제와 알고리즘이 동일하다. 또 못푼건 함정 ㅎㅎ....
[leetcode 85] Maximal Rectangle
Given a rows x cols binary matrix filled with 0's and 1's, find the largest rectangle containing only 1's and return its area. 직사각형 최대 넓이 찾기 Example 1: Input: matrix = [["1","0","..
eazymean.tistory.com
class Solution {
public int largestRectangleArea(int[] heights) {
Stack<Integer> stk = new Stack<Integer>();
int result = 0;
int i=0;
while(i<heights.length){
if(stk.isEmpty() || heights[stk.peek()] <= heights[i]){
stk.push(i);
i++;
}else {
int top = stk.pop();
int area = heights[top] * (stk.isEmpty()? i: (i-stk.peek()-1));
result = Math.max(result, area);
}
}
while(!stk.empty()){
int top = stk.pop();
int area = heights[top] * (stk.isEmpty()? i: (i-stk.peek()-1));
result = Math.max(result, area);
}
return result;
}
}
'알고리즘 문제풀이 > leetcode' 카테고리의 다른 글
[leetcode 239] Sliding Window Maximum (0) | 2020.11.09 |
---|---|
[leetcode 76] Minimum Window Substring (0) | 2020.11.09 |
[leetcode 38] Count and Say (0) | 2020.11.08 |
[leetcode 73] Set Matrix Zeroes (0) | 2020.11.07 |
[leetcode 4] Median of Two Sorted Arrays (0) | 2020.11.07 |
댓글