Skip to content

Instantly share code, notes, and snippets.

@dvnlgls
Created April 20, 2019 23:17
Show Gist options
  • Save dvnlgls/729768d5de5a46ca517c20889a72c75d to your computer and use it in GitHub Desktop.
Save dvnlgls/729768d5de5a46ca517c20889a72c75d to your computer and use it in GitHub Desktop.
Max rectangle in a histogram
// o(n)
// https://stackoverflow.com/a/26202717
// read this: https://stackoverflow.com/a/50651622/336431
function getMaxRect(heights) {
const stack = [];
let max = 0;
let i = 0;
while (i < heights.length) {
if (stack.length === 0 || (stack.length > 0 && heights[stack[stack.length - 1]] <= heights[i])) {
stack.push(i++);
} else {
let top_area = heights[stack.pop()] * (stack.length === 0 ? i : (i - stack[(stack.length - 1)] - 1));
max = Math.max(max, top_area)
}
}
while (stack.length > 0) {
let top_area = heights[stack.pop()] * (stack.length === 0 ? i : (i - stack[(stack.length - 1)] - 1));
max = Math.max(max, top_area)
}
return max;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment