Created
April 20, 2019 23:17
-
-
Save dvnlgls/729768d5de5a46ca517c20889a72c75d to your computer and use it in GitHub Desktop.
Max rectangle in a histogram
This file contains 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
// 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