Skip to content

Commit 35cdd2f

Browse files
refactor 84
1 parent 397e648 commit 35cdd2f

File tree

1 file changed

+20
-33
lines changed
  • src/main/java/com/fishercoder/solutions

1 file changed

+20
-33
lines changed

src/main/java/com/fishercoder/solutions/_84.java

Lines changed: 20 additions & 33 deletions
Original file line numberDiff line numberDiff line change
@@ -2,43 +2,30 @@
22

33
import java.util.Stack;
44

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-
*/
185
public class _84 {
196

20-
public static class Solution1 {
7+
public static class Solution1 {
218

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;
3828
}
39-
}
40-
return maxArea;
4129
}
42-
}
4330

4431
}

0 commit comments

Comments
 (0)