var largestRectangleArea = function(heights, maxArea = 0) {
for (let i = 0; i < heights.length; i++) {
for (let j = i; j < heights.length; j++) {
let min = Infinity;
for (let k = i; k <= j; k++) {
min = Math.min(min, heights[k]);
}
const area = min * ((j - i) + 1);
maxArea = Math.max(maxArea, area);
}
}
return maxArea;
}
var largestRectangleArea = function(heights, maxArea = 0) {
for (let i = 0; i < heights.length; i++) {
let min = Infinity;
for (let j = i; j < heights.length; j++) {
min = Math.min(min, heights[j]);
const area = min * ((j - i) + 1);
maxArea = Math.max(maxArea, area);
}
}
return maxArea;
}
var largestRectangleArea = function(heights, left = 0, right = (heights.length - 1)) {
const isBaseCase = right < left;
if (isBaseCase) return 0;
return divideAndConquer(heights, left, right);
}
const divideAndConquer = (heights, left, right, min = left) => {
for (let i = left; i <= right; i++) {
const isMinGreater = heights[i] < heights[min];
if (!isMinGreater) continue;
min = i;
}
const window = (right - left) + 1;
const area = heights[min] * window;
const leftArea = largestRectangleArea(heights, (min + 1), right)
const rightArea = largestRectangleArea(heights, left, (min - 1))
return Math.max(area, leftArea, rightArea);
}
var largestRectangleArea = function(heights) {
const { stack, maxArea } = fillStack(heights);
return getMaxArea(heights, stack, maxArea);
};
const fillStack = (heights, stack = [], maxArea = 0) => {
for (let index = 0; index < heights.length; index++) {
let start = index;
const isCurrHeightLess = ([ prevIndex, prevHeight ], currHeight) => currHeight < prevHeight;
const canShrink = () => isCurrHeightLess(stack[stack.length - 1], heights[index]);
while (stack.length && canShrink()) {
const [ _index, _height ] = stack.pop();
const width = index - _index;
const area = _height * width;
maxArea = Math.max(maxArea, area);
start = _index;
}
stack.push([ start, heights[index] ]);
}
return { stack, maxArea }
}
const getMaxArea = (heights, stack, maxArea) => {
for (const [ index, height ] of stack) {
const width = heights.length - index;
const area = height * width;
maxArea = Math.max(maxArea, area);
}
return maxArea;
}