|
2 | 2 |
|
3 | 3 | import java.util.Stack;
|
4 | 4 |
|
5 |
| -/** |
6 |
| - * 84. Largest Rectangle in Histogram |
7 |
| - * |
8 |
| - * Given n non-negative integers representing the histogram's bar height where |
9 |
| - * the width of each bar is 1, find the area of largest rectangle in the histogram. |
10 |
| -
|
11 |
| - Above is a histogram where width of each bar is 1, given height = [2,1,5,6,2,3]. |
12 |
| - The largest rectangle is shown in the shaded area, which has area = 10 unit. |
13 |
| -
|
14 |
| - For example, |
15 |
| - Given heights = [2,1,5,6,2,3], |
16 |
| - return 10. |
17 |
| - */ |
18 | 5 | public class _84 {
|
19 | 6 |
|
20 |
| - public static class Solution1 { |
| 7 | + public static class Solution1 { |
21 | 8 |
|
22 |
| - /** |
23 |
| - * credit: https://leetcode.com/articles/largest-rectangle-histogram/#approach-5-using-stack-accepted |
24 |
| - * and https://discuss.leetcode.com/topic/7599/o-n-stack-based-java-solution |
25 |
| - */ |
26 |
| - public int largestRectangleArea(int[] heights) { |
27 |
| - int len = heights.length; |
28 |
| - Stack<Integer> s = new Stack<>(); |
29 |
| - int maxArea = 0; |
30 |
| - for (int i = 0; i <= len; i++) { |
31 |
| - int h = (i == len ? 0 : heights[i]); |
32 |
| - if (s.isEmpty() || h >= heights[s.peek()]) { |
33 |
| - s.push(i); |
34 |
| - } else { |
35 |
| - int tp = s.pop(); |
36 |
| - maxArea = Math.max(maxArea, heights[tp] * (s.isEmpty() ? i : i - 1 - s.peek())); |
37 |
| - i--; |
| 9 | + /** |
| 10 | + * credit: https://leetcode.com/articles/largest-rectangle-histogram/#approach-5-using-stack-accepted |
| 11 | + * and https://discuss.leetcode.com/topic/7599/o-n-stack-based-java-solution |
| 12 | + */ |
| 13 | + public int largestRectangleArea(int[] heights) { |
| 14 | + int len = heights.length; |
| 15 | + Stack<Integer> s = new Stack<>(); |
| 16 | + int maxArea = 0; |
| 17 | + for (int i = 0; i <= len; i++) { |
| 18 | + int h = (i == len ? 0 : heights[i]); |
| 19 | + if (s.isEmpty() || h >= heights[s.peek()]) { |
| 20 | + s.push(i); |
| 21 | + } else { |
| 22 | + int tp = s.pop(); |
| 23 | + maxArea = Math.max(maxArea, heights[tp] * (s.isEmpty() ? i : i - 1 - s.peek())); |
| 24 | + i--; |
| 25 | + } |
| 26 | + } |
| 27 | + return maxArea; |
38 | 28 | }
|
39 |
| - } |
40 |
| - return maxArea; |
41 | 29 | }
|
42 |
| - } |
43 | 30 |
|
44 | 31 | }
|
0 commit comments