Skip to content

Instantly share code, notes, and snippets.

@zcwang
Created July 17, 2018 01:20
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save zcwang/6a0589a1837bc6d9564ce20ce9af3e60 to your computer and use it in GitHub Desktop.
Save zcwang/6a0589a1837bc6d9564ce20ce9af3e60 to your computer and use it in GitHub Desktop.
Largest rectangle area in data histogram
class Solution {
public int largestRectangleArea(int[] heights) {
Stack<Integer> s = new Stack<>();
int result = 0;
for (int i = 0; i <= heights.length; ) {
final int value = i < heights.length ? heights[i] : 0;
if (s.isEmpty() || value > heights[s.peek()]) {
s.push(i++);
} else {
int tmp = s.pop();
result = Math.max(result,
heights[tmp] * (s.isEmpty() ? i : i - s.peek() - 1));
}
}
return result;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment