
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.
1using System;
2using System.Collections.Generic;
3
4public class Solution {
5 public int LargestRectangleArea(int[] heights) {
6 Stack<int> stack = new Stack<int>();
7 int max_area = 0;
8 int i = 0;
9 while (i < heights.Length) {
10 if (stack.Count == 0 || heights[i] >= heights[stack.Peek()]) {
11 stack.Push(i++);
12 } else {
13 int height = heights[stack.Pop()];
14 int width = stack.Count == 0 ? i : i - stack.Peek() - 1;
15 max_area = Math.Max(max_area, height * width);
16 }
17 }
18 while (stack.Count > 0) {
19 int height = heights[stack.Pop()];
20 int width = stack.Count == 0 ? i : i - stack.Peek() - 1;
21 max_area = Math.Max(max_area, height * width);
22 }
23 return max_area;
24 }
25
26 public static void Main(String[] args) {
27 Solution sol = new Solution();
28 int[] heights = {2, 1, 5, 6, 2, 3};
29 Console.WriteLine(sol.LargestRectangleArea(heights)); // Outputs 10
30 }
31}The C# implementation uses a stack, ensuring that at every shorter height encountered or the end of the list, rectangle height and width are computed and their product considered for updating the maximum area observation. The logic uniformly applies whether heights are being appended to the stack or removed for rectangle area estimation and that ensures all cases are handled uniformly.
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 Java solution continues the divide and conquer tradition, using the recursive means to split and evaluate rectangle formation around minimal height indices. The Math.max functionality assists in ensuring the largest area is computed matching all relevant subarray considerations.