• Source
    1. // C++ program to find maximum rectangular area in linear time
    2. #include<iostream>
    3. #include<stack>
    4. using namespace std;
    5.  
    6. // The main function to find the maximum rectangular area under given
    7. // histogram with n bars
    8. int getMaxArea(int hist[], int n)
    9. {
    10. // Create an empty stack. The stack holds indexes of hist[] array
    11. // The bars stored in stack are always in increasing order of their
    12. // heights.
    13. stack<int> s;
    14.  
    15. int max_area = 0; // Initalize max area
    16. int tp; // To store top of stack
    17. int area_with_top; // To store area with top bar as the smallest bar
    18.  
    19. // Run through all bars of given histogram
    20. int i = 0;
    21. while (i < n)
    22. {
    23. // If this bar is higher than the bar on top stack, push it to stack
    24. if (s.empty() || hist[s.top()] <= hist[i])
    25. s.push(i++);
    26.  
    27. // If this bar is lower than top of stack, then calculate area of rectangle
    28. // with stack top as the smallest (or minimum height) bar. 'i' is
    29. // 'right index' for the top and element before top in stack is 'left index'
    30. else
    31. {
    32. tp = s.top(); // store the top index
    33. s.pop(); // pop the top
    34.  
    35. // Calculate the area with hist[tp] stack as smallest bar
    36. area_with_top = hist[tp] * (s.empty() ? i : i - s.top() - 1);
    37.  
    38. // update max area, if needed
    39. if (max_area < area_with_top)
    40. max_area = area_with_top;
    41. }
    42. }
    43.  
    44. // Now pop the remaining bars from stack and calculate area with every
    45. // popped bar as the smallest bar
    46. while (s.empty() == false)
    47. {
    48. tp = s.top();
    49. s.pop();
    50. area_with_top = hist[tp] * (s.empty() ? i : i - s.top() - 1);
    51.  
    52. if (max_area < area_with_top)
    53. max_area = area_with_top;
    54. }
    55.  
    56. return max_area;
    57. }
    58.  
    59. // Driver program to test above function
    60. int main()
    61. {
    62. int hist[] = {6, 2, 5, 4, 5, 1, 6};
    63. int n = sizeof(hist)/sizeof(hist[0]);
    64. cout << "Maximum area is " << getMaxArea(hist, n);
    65. return 0;
    66. }