
Sponsored
Sponsored
This approach utilizes a monotonic stack to efficiently track the heights of the histogram bars. By iterating through the array and maintaining a stack of indices, we can pop the stack whenever we find a shorter bar, calculate the area of the rectangle formed with the popped bar as the shortest.bar and update the maximum area if necessary. The stack helps to find the left and right boundaries for each bar to compute the area.
Time Complexity: O(n), where n is the number of bars (height array length), since each bar is pushed and popped from the stack at most once.
Space Complexity: O(n) for the stack.
1var largestRectangleArea = function(heights) {
2 let stack = [];
3 let maxArea = 0;
4 let i = 0;
5 while (i < heights.length || stack.length) {
6 if (i < heights.length && (stack.length === 0 || heights[i] >= heights[stack[stack.length - 1]])) {
7 stack.push(i++);
8 } else {
9 let height = heights[stack.pop()];
10 let width = stack.length === 0 ? i : i - stack[stack.length - 1] - 1;
11 maxArea = Math.max(maxArea, height * width);
12 }
13 }
14 return maxArea;
15};
16
17// Example usage
18console.log(largestRectangleArea([2, 1, 5, 6, 2, 3])); // Output: 10The JavaScript solution is built around stack operations to manage bar indices effectively. When a lower bar is detected or at the end of the array, the areas using the bars in the current stack setup are calculated, using the indices to compute necessary widths. This efficient processing is backed by the fact that each index enters and exits the stack only once during the entire traversal of heights.
This approach is inspired by the algorithm for finding the maximum subarray sum, with the core idea to exploit the properties of minimal elements acting as the constraints. Here, smaller segments of the array are divided to compute maximum rectangular areas separately and then to combine comprehensive results. It works optimally when the heights array is transformed to assist binary division, allowing recursive calls to determine the peak areas between and within divisions.
Time Complexity: O(n^2), with potential for worse case involving complete traversal checks.
Space Complexity: O(n) for recursive calls.
The C code employs a recursive divide and conquer methodology, recursively finding the minimum height in each segment as a pivot for maximal rectangle widths. It calculates areas recursively, thereby considering left and right segments separated by previously determined minimal height - or "pivot" - as the rectangular height at that segment.