1 public class Solution 2 { 3 public int LargestRectangleArea(int[] hist) 4 { 5 // The main function to find the 6 // maximum rectangular area under 7 // given histogram with n bars 8 int n = hist.Length; 9 // Create an empty stack. The stack 10 // holds indexes of hist[] array 11 // The bars stored in stack are always 12 // in increasing order of their heights. 13 Stack<int> s = new Stack<int>(); 14 15 int max_area = 0; // Initialize max area 16 int tp; // To store top of stack 17 int area_with_top; // To store area with top 18 // bar as the smallest bar 19 20 // Run through all bars of 21 // given histogram 22 int i = 0; 23 while (i < n) 24 { 25 // If this bar is higher than the 26 // bar on top stack, push it to stack 27 if (s.Count == 0 || hist[s.Peek()] <= hist[i]) 28 { 29 s.Push(i++); 30 } 31 32 // If this bar is lower than top of stack, 33 // then calculate area of rectangle with 34 // stack top as the smallest (or minimum 35 // height) bar. 'i' is 'right index' for 36 // the top and element before top in stack 37 // is 'left index' 38 else 39 { 40 tp = s.Peek(); // store the top index 41 s.Pop(); // pop the top 42 43 // Calculate the area with hist[tp] 44 // stack as smallest bar 45 area_with_top = hist[tp] * 46 (s.Count == 0 ? i : i - s.Peek() - 1); 47 48 // update max area, if needed 49 if (max_area < area_with_top) 50 { 51 max_area = area_with_top; 52 } 53 } 54 } 55 56 // Now pop the remaining bars from 57 // stack and calculate area with every 58 // popped bar as the smallest bar 59 while (s.Count > 0) 60 { 61 tp = s.Peek(); 62 s.Pop(); 63 area_with_top = hist[tp] * 64 (s.Count == 0 ? i : i - s.Peek() - 1); 65 66 if (max_area < area_with_top) 67 { 68 max_area = area_with_top; 69 } 70 } 71 72 return max_area; 73 } 74 }
参考:https://www.geeksforgeeks.org/largest-rectangle-under-histogram/