JavaScript Using Stack Beat 97%
Time Complexity = O(N)\nSpace Complexity = O(N)\njavascript\nvar largestRectangleArea = function(heights) {\n    // to deal with last element without going out 
Time Complexity = O(N)\nSpace Complexity = O(N)\n```javascript\nvar largestRectangleArea = function(heights) {\n    // to deal with last element without going out of bound\n    heights.push(0)\n    const stack = [];\n    let maxArea = 0, curr, currH, top, topH, area;\n    \n    for(let i = 0; i < heights.length; i++) {\n        top = stack[stack.length-1];\n        topH = heights[top];\n        // pop from stack as long as the top of the stack\n        // is greater than the current height and\n        // the stack has at least 2 items\n        while(stack.length > 1 && topH > heights[i]) {\n            curr = stack.pop();\n            currH = heights[curr];\n            top = stack[stack.length-1];\n            topH = heights[top];\n            area = currH * (i - 1 - top);\n            maxArea = Math.max(area, maxArea);\n        }\n        \n        // when only 1 item left in the stack\n        if(stack.length && topH > heights[i]) {\n            curr = stack.pop();\n            currH = heights[curr];\n            area = currH * i;\n            maxArea = Math.max(area, maxArea);\n        }\n        stack.push(i);\n    }\n    return maxArea;\n};\n```
['JavaScript']