Created
July 17, 2018 01:20
-
-
Save zcwang/6a0589a1837bc6d9564ce20ce9af3e60 to your computer and use it in GitHub Desktop.
Largest rectangle area in data histogram
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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