Last active
September 6, 2018 08:10
-
-
Save vinicius5581/181b4457b3397713b4c9bfac919db6e8 to your computer and use it in GitHub Desktop.
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
function maxSquareWithinHistoragram(historagram) { | |
let maxArea = 0; | |
const barStack = []; | |
let i = 0; | |
while (i < historagram.length) { | |
if (!barStack.length || historagram[barStack[barStack.length - 1]] <= historagram[i]) { | |
barStack.push(i); | |
i++; | |
} else { | |
const currentHeight = historagram[barStack.pop()]; | |
const currentWidth = !barStack.length ? i : i - 1 - barStack[barStack.length - 1]; | |
const area = currentHeight * currentWidth; | |
if (area > maxArea) { | |
maxArea = area; | |
} | |
} | |
} | |
while (barStack[barStack.length - 1]) { | |
const currentHeight = historagram[barStack.pop()]; | |
const currentWidth = !barStack.length ? i : i - 1 - barStack[barStack.length - 1]; | |
const area = currentHeight * currentWidth; | |
if (area > maxArea) { | |
maxArea = area; | |
} | |
} | |
return maxArea; | |
} | |
const historagramSample = [5, 3, 4, 4, 1, 9]; | |
console.log(maxSquareWithinHistoragram(historagramSample)); // 12 |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment