JSFiddle - React, Tailwind, and code Playground
by Bhesh Gurung
JavaScript
function largetRect(hist) {
var h, pos, tempH, tempPos, tempSize = 0, maxSize = -Infinity;
var hStack = [], pStack = [];
function popThatShi() {
tempH = hStack.pop();
tempPos = pStack.pop();
tempSize = tempH * (pos - tempPos);
maxSize = Math.max(tempSize, maxSize);
}
for (pos = 0; pos < hist.length; pos++) {
h = hist[pos];
if (hStack.length === 0 || h > hStack[hStack.length - 1]) {
hStack.push(h);
pStack.push(pos);
} else if (h < hStack[hStack.length - 1]) {
while(hStack.length && h < hStack[hStack.length - 1]) {
popThatShi();
}
if(hStack.length === 0) {
hStack.push(h);
pStack.push(tempPos);
}
}
}
while(hStack.length) {
popThatShi();
}
return maxSize;
}
alert(largetRect([2, 1, 5, 6, 4, 4, 3]));